In PHP, operator precedence determines the order in which operations are performed in an expression. Just like in mathematics, some operations are performed before others. For example, in the expression “2 + 3 * 4”, the multiplication operation (3 * 4) is performed before the addition operation (2 + 12).
Operator precedence can be affected by the use of parentheses. Parentheses can be used to override the default precedence of operators and force a certain order of operations. For example, in the expression “2 + (3 * 4)”, the multiplication operation is performed within the parentheses, and then the result is added to 2.
The following table lists the operators in PHP, in order of precedence from highest to lowest:
- ** (exponentiation)
- ++ (increment)
- — (decrement)
- (type) (type casting)
- ! (not)
- ~ (bitwise not)
-
- (unary plus)
-
- (unary minus)
- . (string concatenation)
-
- (multiplication)
- / (division)
- % (modulus)
-
- (addition)
-
- (subtraction)
- .= (string concatenation assignment)
- << (bitwise left shift)
-
(bitwise right shift)
- < (less than)
-
(greater than)
- <= (less than or equal to)
-
= (greater than or equal to)
- <> (not equal to)
- != (not equal to)
- === (identical)
- !== (not identical)
- & (bitwise and)
- ^ (bitwise xor)
- | (bitwise or)
- && (logical and)
- || (logical or)
- ?: (ternary)
- = (assignment)
- += (addition assignment)
- -= (subtraction assignment)
- *= (multiplication assignment)
- /= (division assignment)
- %= (modulus assignment)
- &= (bitwise and assignment)
- ^= (bitwise xor assignment)
- |= (bitwise or assignment)
- <<= (bitwise left shift assignment)
-
= (bitwise right shift assignment)
It is important to be aware of operator precedence when writing expressions in PHP. Using parentheses can help make your code easier to read and understand by explicitly specifying the order of operations.