PHP Reference ยท Operators
PHP operator precedence and associativity
Reference for PHP operator precedence and associativity: the full table from clone and new down to or, plus classic traps with and, ., ?? and **.
Precedence decides which operator in an expression is applied first. Associativity decides the order when operators of equal precedence meet: 10 - 4 - 3 is left-associative, so it means (10 - 4) - 3, while 2 ** 3 ** 2 is right-associative and means 2 ** (3 ** 2).
You do not need to memorize the table. Use parentheses whenever an expression mixes different kinds of operators; they cost nothing and make the intent obvious. Knowing the table helps you read other people's code and spot the few traps listed below.
echo 1 + 2 * 3; // 7, because * binds tighter than + echo (1 + 2) * 3; // 9
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
The precedence table
From highest to lowest. Operators in the same row have equal precedence.
| Associativity | Operators |
|---|---|
| n/a | clone, new |
| right | ** |
| n/a | ++, --, ~, (int) and other casts, @, unary + and - |
| left | instanceof |
| n/a | ! |
| left | *, /, % |
| left | +, - |
| left | <<, >> |
| left | . (concatenation, lower than arithmetic since PHP 8) |
| non-associative | <, <=, >, >= |
| non-associative | ==, !=, ===, !==, <>, <=> |
| left | & |
| left | ^ |
| left | | |
| left | && |
| left | || |
| right | ?? |
| non-associative | ? : (ternary) |
| right | =, +=, -=, *=, **=, /=, .=, %=, &=, |=, ^=, <<=, >>=, ??= |
| n/a | yield from, yield, print |
| left | and |
| left | xor |
| left | or |
Usage notes
and,orandxorsit below=.$ok = $a and $bassigns$afirst. Use&&and||for conditions, and keepand/orfor flow-control idioms such asopen() or die().**binds tighter than unary minus.-2 ** 2is-4..is lower than+and-since PHP 8."a" . 1 + 2is"a3", but add parentheses so nobody has to remember.- Comparison operators do not chain.
1 < 2 < 3is a syntax error. - Nested ternaries need parentheses.
a ? b : c ? d : ewithout parentheses is a fatal error since PHP 8. Usematchfor multi-way choices. - Bitwise operators rank below comparison.
$flags & MASK === 0compares first. Parenthesize bitwise tests. ??is right-associative and lower than.,+and comparisons.- Order of evaluation is separate from precedence. In
$i + $i++PHP does not promise which operand is read first; avoid side effects inside one expression. - Assignment is an expression.
$a = $b = 3works because=is right-associative.