Validation using OR condition vs in_array in php

I have this validation for gender, I use the OR condition because it will only test 2 condition if male or female but I can't figure out why it throws the error in the OR condition but if in_array was used it works just fine, here is the code:

// If OR condition was used display, is Not a valid gender
<?php
if(empty($_POST['gender']))
{
   $genderError = "*Gender is required";
}

else
{
   $gender = $_POST['gender'];

   if ($gender != 'Male' || $gender != 'Female')
     $genderError = "Not a valid gender";
}
?>

// Using in_array works fine
<?php
if(empty($_POST['gender']))
{
   $genderError = "*Gender is required";
}

else
{
   $gender = $_POST['gender'];
   $genderArray = array('Male', 'Female');

   if (!inarray($gender,$genderArray))
     $genderError = "Not a valid gender";
}
?>

<input type="radio" name="gender" checked value="Male">Male
<input type="radio" name="gender" value="Female">Female

1 answer

  • answered 2018-05-16 05:49 M Khalid Junaid

    You need && instead of || operation because if $gender has value Male then it will satisfy your second criteria that is $gender != 'Female' clause and shows error.

    if ($gender != 'Male' && $gender != 'Female'){
     // some other value, throw error
    }
    

    For simplicity i would go with in_array approach