The following code:
$result = (false or true);
echo("With extra parentheses: ".($result?"true":"false"));
$result = false or true;
echo("<br />With no parentheses: ".($result?"true":"false"));
generates the output:
With extra parentheses: true
With no parentheses: false
I do not understand why. Shouldn't php evaluate $result = false or true;
by first testing false
and then, since it isn't true, going on to evaluate true
?
Any suggestions would be much appreciated.
The or
operator has a weaker precedence than the assignment operator. What really happens in the second case is ($result = false) or true
, so the part or true
really has no effect.
The assignment operator yields the assigned value as its result, false
in this case. Think of the assignment operator as an ordinary binary operator that yields a result (like +
, <
and or
), with the only difference that it has a side effect.
If you want to avoid the parentheses, you can swap or
for ||
, which has a stronger precedence.
Always be careful when using the English versions of the logical operators, because their precedence is different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With