You are currently viewing PHP Operator Precedence and Associativity
  • Post category:PHP

PHP Operator Precedence and Associativity

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.

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.

Precedence Operator Associativity
1 () I-O & L-R
2 clone new Non-Associative
3 ** R-L
4 ++ — ~ (datatype) R-L
5 instanceof Non Associative
6 ! R-L
7 * / % L-R
8 + – . L-R
9 <<>> L-R
10 <  <=  >  >= Non Associative
11 == != === !== <> <=> Non Associative
12 & L-R
13 ^ L-R
14 | L-R
15 && L-R
16 || L-R
17 ?: L-R
18 = += -= *= **= /= %= .= &= |= <<=  >>= R-L
19 and L-R
20 xor L-R
21 or L-R
READ ALSO  3 Best Ways to get the first character of string in PHP

Note:

Operators with equal precedence and non-associative should not be used next to each other.

Ex: 1<2>3

Leave a Reply