开发者

I cannot compare two strings in PHP

    <?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?


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";


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.


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"


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"


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)) {... 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜