I came across some code today where a string is compared to two values at the same time. I’ve never seen this before – will this work? Can someone explain it to me?
$foo = 'date';
if ($foo == ('date' || 'datetime')) {
echo "Hello world";
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That won’t work. Write
if ($foo == 'date' || $foo == 'datetime').Not only won’t
||work for selecting from a set, but also youuseused a single=, which is for assignment rather than comparison.In this case, the constant strings are compared using the boolean or operator. To do that, they are both converted to boolean. Since they are non-empty strings, they evaluate to
true. true or true returns true,which is assigned towhich is compared to $foo. That comparison will always be true if $foo is ‘date’ or ‘datetime’ or about any other non-empty string.$fooSo, whatever the previous value of $foo was, or even if it wasn’t assigned at all, the if-expression always evaluates to true, so you always get the echo, and $foo will always be
trueafterwards.