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
oroperator has a weaker precedence than the assignment operator. What really happens in the second case is($result = false) or true, so the partor truereally has no effect.The assignment operator yields the assigned value as its result,
falsein this case. Think of the assignment operator as an ordinary binary operator that yields a result (like+,<andor), with the only difference that it has a side effect.If you want to avoid the parentheses, you can swap
orfor||, which has a stronger precedence.Always be careful when using the English versions of the logical operators, because their precedence is different.