PHP - What is Operator Precedence

Introduction

Consider the following example:

3 + 4 * 5

Is PHP supposed to add 3 to 4 to produce 7, then multiply the result by 5 to produce a final figure of 35?

Or should it multiply 4 by 5 first to get 20, then add 3 to make 23?

All PHP operators are ordered according to precedence.

An operator with a higher precedence is executed before an operator with lower precedence.

In the case of the example, * has a higher precedence than + , so PHP multiplies 4 by 5 first, then adds 3 to the result to get 23.

Here's a list of all the operators you've encountered so far, in order of precedence (highest first):

  • ++ -- (increment/decrement)
  • (int) (float) (string) (array) (object) (bool) (casting)
  • ! (not)
  • * / % (arithmetic)
  • + - . (arithmetic)
  • < <=> >= <> (comparison)
  • == != === !== (comparison)
  • && (and)
  • || (or)
  • = += -= *= /= .= %= (assignment)
  • and
  • xor
  • or

You can change the order of execution of operators in an expression by using parentheses.

Parentheses forces that operator to take highest precedence.

So, for example, the following expression evaluates to 35:

( 3 + 4 ) * 5

Logic operator

PHP has two logical "and" operators (&&, and) and two logical "or" operators (||, or).

&& || have a higher precedence than and or.

and and or are below even the assignment operators.

This means that you have to be careful when using and and or.

For example:

$x = false || true; // $x is true
$x = false or true; // $x is false

In the first line, false || true evaluates to true , so $x ends up with the value true.

In the second line, $x = false is evaluated first, because = has a higher precedence than or.

By the time false or true is evaluated, $x has already been set to false.

It is a good idea to stick with && and || unless you specifically need that low precedence.

Related Topic