Strange ways "or" in PHP

PHP or is a weird keyword. Here it is in the code snippet that confuses me:

 echo 0 or 1; // prints 1 $foo = (0 or 1); echo $foo; // prints 1 $foo = 0 or 1; echo $foo; // prints 0 for some reason 

Why does the latter print 0, not 1?

+7
php
source share
7 answers

This is due to the different priority of the operator. In the third case, the appointment is performed first. It will be interpreted as follows:

 ($foo = 0) or 1; 

Operator || has a different priority. If you use

  $foo = 0 ||1; 

It will work as you expect.

See manual for logical operators.

+21
source share

No, I would not do this, because the operator's priority :

  $foo = 0 or 1; // is same as ($foo = 0) or 1; // because or has lower precedence than = $foo = 0 || 1; // is same as $foo = (0 || 1); // because || has higher precedence than = // where is this useful? here: $result = mysql_query() or die(mysql_error()); // displays error on failed mysql_query. // I don't like it, but it okay for debugging whilst development. 
+5
source share

This is ($foo = 0) or 1; . or has lower operator precedence than = .

In this case you should use || , since it has a higher priority than = , and therefore will be evaluated as you expected.

+4
source share

IIRC, the assignment operator ( = ) takes precedence over or . Thus, the last line will be interpreted as:

 ($foo = 0) or 1; 

This is an operator that assigns 0 to $foo , but returns 1. The operator of the first action is interpreted as:

 echo(0 or 1); 

As such will print 1.

0
source share

The order of operations. The word "or" has a much lower priority than the corresponding "||". Lower, even than assignment operator. Thus, the assignment occurs first, and the assignment value is the first operand to "or".

"or" means more for flow control than for logical operations. It lets you say something like

 $x = get_something() or die("Couldn't do it!"); 

if get_something is encoded to return false or 0 on error.

0
source share

In the first two snippets, you compare 0 or 1 (essentially true or false). In the third fragment, you assign 0, which works and thus is true, so the condition or condition is not satisfied. Character text

0
source share

In your third example, the = operator has higher precedence than or, and thus is done first. || the operator, apparently identical, has a higher priority than =. As you say, interesting.

0
source share

All Articles