The precedence of an operator specifies how "tightly" it binds two expressions together.
In general, operators have a set precedence, or order, in which they are evaluated.
For example, in the expression
10 + 5 * 2, the answer is
20 and not
30 because the multiplication
* operator has a higher precedence than the addition
() may be used to force precedence, if necessary. For instance:
(10 + 5) * 2 evaluates to
Operators also have an associativity.
When operators have equal precedence their associativity decides how the operators are grouped.
- is left-associative, so
1 - 2 - 3 is grouped as
(1 - 2) - 3 and evaluates to
= is right-associative, so
$a = $b = $c is grouped as
$a = ($b = $c).
Following Table shows operator precedence and associativity in PHP, where operators with the lowest precedence are at the top, and precedence increases as you go down the table.
<?php $n1 = 10; $n2 = 5; $n3 = 2; $ans = $n1 + $n2 * $n3; # * has higher precedence than + # so first execute $n2 * $n3 the # answer is added to $n1 which is echo "$n1 + $n2 * $n3 = $ans<br />"; $ans = ($n1 + $n2) * $n3; # () has higher precedence than * so bracket execute first # which is ($n1 + $n2) after addition answer is # multiplied by $n3 */ echo "($n1 + $n2) * $n3 = $ans<br />"; ?>