Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php "if" condition mystery

I am running into a funny problem with a mischievous "if" condition :

$condition1="53==56";
$condition2="53==57";
$condition3="53==58";
$condition=$condition1."||".$condition2."||".$condition3;
if($condition)
{
    echo "blah";
}
else
{
    echo "foo";
}

Why does the if condition pass? Why does php echo "blah"? What do I do to make php evaluate the "if" statement and print "foo"?

like image 524
sniper Avatar asked Nov 27 '22 03:11

sniper


2 Answers

The problem here is that you're putting your expressions in strings!

Your $condition1, $condition2, and $condition3 variables contain strings, and not the result of an expression, and the same goes for your $condition variable which will be a string that looks like 53==56||53==57||53==58. When PHP evaluates a string it considers it true if it is not empty and not equal to 0, so your script will output blah.

To fix this you just need to take your expressions out of the strings. It should look like this:

$condition1 = 53 == 56; // false
$condition2 = 53 == 57; // false
$condition3 = 53 == 58; // false
$condition = $condition1 || $condition2 || $condition3; // false || false || false = false

if ($condition) {
    echo 'blah';
} else {
    echo 'foo'; // This will be output
}
like image 155
Calvin Davis Avatar answered Nov 29 '22 17:11

Calvin Davis


You're evaluating strings as booleans; they'll aways be true (except the strings "" and "0". Get rid of almost all of the quotes in your program.

like image 38
Wooble Avatar answered Nov 29 '22 16:11

Wooble