开发者

Usage of or operator in php?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜