Please wait

Operator Precedence

Operator precedence in PHP, like in mathematics, is the set of rules that dictate the order in which operations are performed in expressions with more than one operator. Understanding operator precedence is important because it helps ensure your expressions are evaluated the way you intend.

To better understand this, consider the math expression 2 + 3 * 4. According to the rules of mathematics (the order of operations), you should perform the multiplication before the addition. So the correct answer is 2 + (3 * 4) = 14, not (2 + 3) * 4 = 20. This rule is an example of operator precedence: multiplication has higher precedence than addition.

Similarly, in PHP, if you write an expression like $result = $a + $b * $c;, PHP will first calculate $b * $c and then add $a to the result because the multiplication operator (*) has higher precedence than the addition operator (+).

Table reference

Here's a complete list of operators and their precedence in PHP. Operators listed at the top of the table have higher precedence. Multiple operators can have the same precedence if listed on the same line.

AssociativityOperatorsAdditional Information
(n/a)clone newclone and new
right**arithmetic
(n/a)+ - ++ -- ~ (int) (float) (string) (array) (object) (bool) @arithmetic (unary + and -), increment/decrement, bitwise, type casting and error control
leftinstanceoftype
(n/a)!logical
left* / %arithmetic
left+ - .arithmetic (binary + and -), array and string (. prior to PHP 8.0.0)
left<< >>bitwise
left.string (as of PHP 8.0.0)
non-associative< <= > >=comparison
non-associative== != === !== <> <=>comparison
left&bitwise and references
left^bitwise
left|bitwise
left&&logical
left||logical
right??null coalescing
non-associative? :ternary (left-associative prior to PHP 8.0.0)
right= += -= *= **= /= .= %= &= |= ^= <<= >>= ??=assignment
(n/a)yield from yield from
(n/a)yieldyield
(n/a)printprint
leftandlogical
leftxorlogical
leftorlogical

We haven't gone over every single operator offered in PHP. Don't worry; as you progress through the book, you'll pick up more operators.

Associativity

In the table above, there's a column called "Associativity." What does it mean? In programming, "associativity" is the property that determines how operators of the same precedence are grouped in the absence of parentheses. It can either be from left to right, which is called "left associativity", or from right to left, which is called "right associativity".

Let's take a look at some examples:

Left Associativity

For example, the + operator:

Even though + operator has the same precedence, it's grouped from left to right because it's left-associative. This means the operation is equivalent to ((1 + 2) + 3), resulting in 6.

$result = 1 + 2 + 3;
 
 
 

Right Associativity

For example, the = operator:

In this case, the '=' operator is right-associative, which means it's grouped from right to left. So, the operation is equivalent to ($a = ($b = ($c = 5))), assigning the value 5 to all the variables.

$a = $b = $c = 5;
 
 
 

Non-associative

Non-associativity in PHP, or in programming in general, refers to operators that can't be chained together in a meaningful way. A good example of this is the comparison operator.

For example, consider the following PHP expressions:

If PHP allowed left-to-right chaining of < operator (i.e., if < was left-associative), then PHP would first evaluate 3 < 4, which is true, and then it would evaluate true < 5. But in PHP, the < operator is non-associative, meaning that you can't chain together comparison operators like this. The correct way to write this would be:

In this way, non-associative operators enforce good programming practice by making sure that certain kinds of expressions are written in a clear and unambiguous way. It's also worth noting that some operators in PHP are non-associative because it doesn't make sense to chain them together. An example is the === operator, which tests for exact equality. It doesn't make sense to say $a === $b === $c, because $a === $b results in a boolean value, and it wouldn't be meaningful to then compare that boolean value with $c for exact equality.

3 < 4 < 5
 
 
 

The concept of associativity helps to remove ambiguity in expressions where the operators have the same precedence. It's crucial to know the associativity of the operators to understand the order in which the operations occur.

Overriding precedence

We can override operator precedence by using parentheses (()). Parentheses are an important tool in programming as they allow you to explicitly specify the order in which operations should be performed, regardless of the normal operator precedence and associativity rules.

By enclosing part of an expression within parentheses, you are telling the program to "do this part first". If there are multiple levels of parentheses, the operations in the innermost parentheses are performed first, then the next level out, and so on.

Here is an example to illustrate how parentheses can change the result of an operation:

Without parentheses

In the example, according to the rules of operator precedence, multiplication (*) is performed before addition (+), so 2 * 3 happens first, and then 1 is added to the result.

$result = 1 + 2 * 3;
echo $result;  // Output will be 7

With parentheses

In this case, the parentheses force the addition operation to happen first, so 1 + 2 is done first, and then the result is multiplied by 3.

$result = (1 + 2) * 3;
echo $result;  // Output will be 9

Thus, parentheses are quite useful when you need to perform specific operations in an expression first or when you want to make your code clearer and more readable. Operator precedence can become more complex with more operators and parentheses. Parentheses can be used to override the default precedence, forcing certain parts of the expression to be evaluated first.

Key takeaways

  • PHP operators follow a specific precedence order. Certain types of operators are evaluated before others. For instance, multiplication and division operations have higher precedence than addition and subtraction.
  • Operator associativity determines the order of operations for operators of the same precedence. It can be left (left to right), right (right to left), or non-associative (operators that cannot be chained together like comparison operators).
  • Parentheses can be used to alter the default precedence order, and they are often used to make the code clearer.
  • PHP's official documentation provides a detailed table of operator precedence and associativity. When in doubt, refer to this resource, which you can find here.

Comments

Please read this before commenting