Home » Php » The strange ways of the "or" in PHP

The strange ways of the "or" in PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

PHP’s or is an weird keyword. Here it is in a code snippet that makes me confused:

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 last one print 0 and not 1?

How to&Answers:

This is because of different operator precedence. In the third case, the assignment is handled first. It will be interpreted like this:

($foo = 0) or 1;

The || operator has a different precedence. If you use

 $foo = 0 ||1;

It will work as you expect.

See the manual on logical operators

Answer:

No, I wouldn’t, that’s because of operator precedence:

 $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's okay for debugging whilst development.

Answer:

It’s ($foo = 0) or 1;. or has a lower operator precedence than = .

You should use || in this case, since it has a higher precedence than =, and thus will evaluate as you’d expect.

Answer:

IIRC, the assignment operator (=) has higher precedence than or. Thus, the last line would be interpreted as:

($foo = 0) or 1;

Which is a statement that assigns 0 to $foo, but returns 1. The fist statement is interpreted as:

echo(0 or 1);

An as such will print 1.

Answer:

Order of operations. The word “or” has much lower precedence than the corresponding “||”. Lower, even, than the assignment operator. So the assignment happens first, and the value of the assignment is the first operand to the “or”.

“or” is meant more to be used 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 coded to return false or 0 on failure.

Answer:

In the first two snippets, you are comparing 0 or 1 (essentially true or false). In the third snippet you are assigning 0, which works, and thus is true, so therefore the or condition is not executed.emphasized text

Answer:

In your third example, the = operator has a higher precedence than or, and thus gets done first. The || operator, superficially the same, has a higher precedence than =. As you say, interesting.