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 doe开发者_如何学运维s the if condition pass? Why does php echo "blah"? What do I do to make php evaluate the "if" statement and print "foo"?
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
}
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.
Those aren't conditions, they're strings.
$condition1=53==56;
$condition2=53==57;
$condition3=53==58;
$condition=$condition1 || $condition2 || $condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Because you're not checking those variables, it's saying if (String)
will always return true. (unless ""
)
You should be doing:
if(53==56 || 53==57 || 53==58)
{
echo "blah";
}
else
{
echo "foo";
}
All $condition*
variables will evaluate to true. This is how PHP sees it:
if("53==56" || "53==57" || "53==58")
What you want is this:
$condition1 = 53==56;
$condition2 = 53==57;
$condition3 = 53==58;
It's because you're evaluating a string, and strings other than empty strings evaluate to true.
You are concatting a string together, a non-empty string equals TRUE
in php.
Because when the if passes, $condition is a string (a concatenation of) containing the text of your conditions. Try using if(eval($condition))
.
String always evaluate to true if its not empty
And btw php make implicit conversion to boolean
精彩评论