PHP Operator Precedence
In this article, we will see about php operator precedence and Associativity.
What is precedence
It determines while evaluating any expression; which operator should be evaluated first before the other. i.e which operator needs to be given higher precedence than the other?
This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher than the addition operator.
For example, consider the expression x= 7+5*2;
Here x is assigned 17, not 24 because operator * has higher precedence than + operator. So first it get multiplied with 5*2 and then adds into 7. Any expression in PHP, higher precedence operators will be evaluated first. If two operators have the same precedence, the evaluation of expression based on left to right or right to left is called associativity.
It determines if the same operator appears one or more times in an expression, and in which direction the specific operator needs to be evaluated.
Precedence and associativity table
The given table summarizes the operators available in PHP. Here highest precedence operators appear at the top of the table and the lowest precedence operators appear at the bottom.
|1||()||I-O & L-R|
|4||++ — ~ (datatype)||R-L|
|7||* / %||L-R|
|8||+ – .||L-R|
|10||< <= > >=||Non Associative|
|11||== != === !== <> <=>||Non Associative|
|18||= += -= *= **= /= %= .= &= |= <<= >>=||R-L|
Operators with equal precedence and non-associative should not be used next to each other.