Php "if" mystery condition

I got confused about the mischievous "if" condition:

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

Why is the if condition satisfied? Why php echo "blah"? What should I do so that php evaluates the if if statement and prints "foo"?

+4
source share
9 answers

The problem is that you put your expressions in strings!

Your $condition1 , $condition2 and $condition3 variables contain strings, not the result of the expression, and the same applies to your $condition variable, which will be a string that looks like 53==56||53==57||53==58 . When PHP evaluates the 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 extract the expressions from 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 } 
+8
source

You evaluate strings as booleans; they will be true (except for the strings "" and "0" . Get rid of almost all the quotes in your program.

+7
source

These are not conditions, they are strings.

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

Since you are not checking these variables, it says that if (String) will always return true. (if "" )

You must do:

 if(53==56 || 53==57 || 53==58) { echo "blah"; } else { echo "foo"; } 
+4
source

All $condition* variables will be evaluated as true. This is how PHP sees it:

 if("53==56" || "53==57" || "53==58") 

What you want is:

 $condition1 = 53==56; $condition2 = 53==57; $condition3 = 53==58; 
+4
source

This is because you evaluate the string, and strings other than empty strings evaluate to true.

+2
source

You concatenate a string together, a non-empty string equals TRUE in php.

+2
source

Because when if passes, $ condition is a string (concatenation) containing the text of your conditions. Try using if(eval($condition)) .

+1
source

A string is always evaluated as true if its not empty And btw php does an implicit conversion to boolean

+1
source

All Articles