Precedence and Associativity
Explore how operator precedence and associativity determine the evaluation order of expressions in PHP. Understand how to read and order arithmetic operations, including how left and right associativity work, to write clearer and more accurate PHP code.
We'll cover the following...
Precedence
Operator precedence determines which operator is performed first in an expression with more than one operators. Operator precedence in PHP is similar to that of regular arithmetic operators.
*,/,%operators have equal precedence.+,-operators have equal precedence.*,/,%have a higher precedence than+,-.
The operator with higher precedence is executed first in the expression.
Associativity
Associativity is used when two operators of the same precedence appear in an expression.
Left Associativity
Left associativity occurs when an expression is evaluated from left to right. For example * and / have the same precedence and their associativity is left to right, so the expression
100 / 10 * 10
is treated as:
(100 / 10) * 10