Last Updated: February 25, 2016
·
2.505K
· belapatkai

PHP operator precedence

The "AND" and "&&" operators seem to be identical, but they have a different precedence. And the same applies to the "OR" and "||" operators:

$result = false || true; // yields "true"
$result = false or true; // yields "false"

3 Responses
Add your response

over 1 year ago ·

This sounds like a clear bug (and another reason to never use 'or' in PHP). Per documentation 'or' should yield 'true' when it's $result = false or true;:

"$a or $b Or TRUE if either $a or $b is TRUE"

http://www.php.net/manual/en/language.operators.logical.php

over 1 year ago ·

From the documentation http://php.net/manual/en/language.operators.logical.php, is pretty clear how or and and work.

Operators like || and && will make the logical comparison between two boolean values.

$a = false || true; // a => true

is equal to:

$a = (false || true); // a => true

But or and and will make a decision in the flow of the program. The or operator will run the second part of the expression only in the first one has failed. For instance:

connect_to_my_db() or die('Nope!');

That's the most common usage for the or operator. But, when we use it for something like this:

$a = false or true; // a => false

This is the wrong way to use this kind of operator. What happens here is that, PHP will try to identify two expressions and it will do it. The first expression is $a = false and the second one is true. Then will consider that the assignment was successful and will not use the second part of the or operation.

So, the equivalent for the previous line of PHP is:

($a = false) or true; // $a => false

The same thing for the and operator, but it'll examine the second part of the operation only in the first one was successful. For example, you can do something like this:

open_my_file() and read_my_file();

Only if the opening of the file has succeeded then it'll read the content of the file.

Is this confusing? Maybe yes. So, this is not a bug, but we're using the language in the wrong way.

over 1 year ago ·