1
    <?php
    $gender = "devilcode";
    if (($gender == "female") || ($gender = "male"))
        {
            echo "ok";
        }
    else echo "no";
    ?>

It should output "no" but it outputs "ok". What am I doing wrong?

Rasika
  • 1,980
  • 13
  • 19
ilhan
  • 8,700
  • 35
  • 117
  • 201
  • Put double equals for $man condition as everybody says. And also put OR instead of ||. Maybe it changes something. And also no need to parentheses for conditions. It should work. – aiternal Mar 13 '11 at 23:26

6 Answers6

13

You are assigning $gender to be male, rather than testing it for comparison, you need two equal signs:

$gender = "devilcode";
if (($gender == "female") || ($gender == "male"))
    echo "ok";
else 
    echo "no";
Jake N
  • 10,535
  • 11
  • 66
  • 112
  • Shouldn't that be the other way round? Assigning one equal sign and comparison two equal signs? – Rasika Mar 13 '11 at 21:45
7

You're missing an equals sign:

($gender == "male")

Edit: For this very reason, many coders suggest writing the comparison the other way around, with the static value on the left:

if ("male" == $gender) { ... }

This way, if you forget and use = instead of ==, you get a syntax error.

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
5

Is the second part of the IF $gender="male"? I think this is returning true always and is causing the problem. Make it $gender=="male"

Rasika
  • 1,980
  • 13
  • 19
2

there is a bug in the second part of your test. replace

($gender = "male") // assign $gender with the value "male"
                   // this is always evaluated to TRUE in your test

by

($gender == "male") // test that $gender is equal to "male"
Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77
1

You are assigning the var $gender to 'male' ($gender = 'male') instead of copmaring it ($gender == 'male')

Also if you want to test against several possible outcomes try in_array()

$gender = 'devilcode'
$genders = array('female','male','unknown')
if(in_array($gender, $genders)){
 echo 'ok';
}else{
 echo 'no';
}

Regards.

Rayvyn
  • 77
  • 1
  • 7
1

Good practice for writing conditions, which protects from errors like this is using inverse notation:

if ('female' === $gender || 'male' === $gender) {...    

or:

$allowed = array('male', 'female', 'unknown');
if (in_array($gender, $allowed)) {... 
takeshin
  • 49,108
  • 32
  • 120
  • 164