Operator precedence or how does 'or die()' work.

  1. A smart interpreter
  2. Operator precedence
  3. The difference between || and OR
  4. Comments (3)

In the old school PHP code you can often see a statement like this:

$result some_function() OR some_other_function();

(sadly, but most of time it features die() as some_other_function(), which is extremely bad practice. Every time you see it, replace die() with trigger_error(), which will give you exactly the same result on your local system but will make the code ready for going live. Read more on the proper error reporting...)

In this statement, some_other_function() would be called only if some_function() fails (or, strictly speaking, returns an empty result).

But how does it actually work? Here you go:

A smart interpreter

A code like this

some expression 1 OR some expression 2;

is just a PHP expression. Exactly the same as

$variable1 $variable1;

and OR operator is just like * (or any other - >, =, . and such) operator.

Most of time we are using the result OR operator in some context, like in the conditional operator

if (some expression 1 OR some expression 2) ...

But if is not obligatory here. We can always omit it, leaving only

 some expression 1 OR some expression 2;

and it will cause no parse error.

And here comes the key part: because OR operator will return TRUE if one of the 2 operands is TRUE, a smart interpreter wouldn't run the second operand at all, if first one already evaluated to TRUE!

So, this is the trick:

 some expression 1 OR some expression 2 ;

means "execute some expression 2 only if some expression 1 returned FALSE"

Operator precedence

Now let's try assign the result of OR operator to some variable

$variable some expression 1 OR some expression 2;

There is a thing called operator precedence. And = operator has a higher precedence than OR and so it will be executed first. Thus, this expression can be written as

($variable some expression 1) OR some expression 2;

So now you can conclude how the whole thing works

Note that logical operators in PHP can be used with any data type, not only Boolean values, due PHP's automatic type conversion:

The difference between || and OR

On a side note, now you can tell why we are using || instead of OR when we want a boolean result but not the trick discussed above. || has lesser precedence than = and thus

$variable some expression 1 || some expression 2;

will be executed the straight way - first we are getting the Boolean result of || and then it gets assigned to $variable. But of course we can always use () braces to manage precedence manually - as braces has the highest precedence of them all, everything inside will be evaluated first.


Related articles: