开发者

Usage of or operator in php?

开发者 https://www.devze.com 2023-03-14 21:40 出处:网络
The following code: $result = (false or true); echo(\"With extra parentheses: \".($result?\"true\":\"false\"));

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

精彩评论

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