Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 994
user810702 Avatar asked Dec 10 '22 07:12

user810702


1 Answers

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.

like image 119
Blagovest Buyukliev Avatar answered Dec 28 '22 22:12

Blagovest Buyukliev