Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Operator Precedence
Operator precedence in PHP determines the order in which operations are evaluated in expressions. Understanding precedence helps you write correct code and avoid unexpected results. For example, in 2+6/3, division happens first (resulting in 2+2=4) because the division operator / has higher precedence than addition +.
How Precedence Works
When operators have the same precedence level, associativity (left-to-right or right-to-left) determines the evaluation order. You can override precedence using parentheses to force specific operations to execute first −
<?php // Without parentheses - multiplication first echo 2 + 3 * 4; // Result: 14 (2 + 12) echo "<br>"; // With parentheses - addition first echo (2 + 3) * 4; // Result: 20 (5 * 4) ?>
14 20
PHP Operator Precedence Table
The following table lists PHP operators in decreasing order of precedence (highest to lowest) −
| Operators | Purpose | Associativity |
|---|---|---|
| clone new | clone and new | none |
| ** | exponentiation | right |
| ++ -- | increment/decrement | none |
| ~ (int) (float) (string) (array) (object) (bool) | casting | right |
| instanceof | type checking | none |
| ! | logical NOT | right |
| * / % | multiplication, division, modulo | left |
| + - . | addition, subtraction, concatenation | left |
| << >> | bitwise shift | left |
| < <= > >= | comparison | none |
| == != === !== <> <=> | equality/comparison | none |
| & | bitwise AND | left |
| ^ | bitwise XOR | left |
| | | bitwise OR | left |
| && | logical AND | left |
| || | logical OR | left |
| ?? | null coalescing | right |
| ? : | ternary conditional | left |
| = += -= *= /= .= %= &= |= ^= <<= >>= | assignment | right |
| and | logical AND (lower precedence) | left |
| xor | logical XOR | left |
| or | logical OR (lower precedence) | left |
Common Precedence Examples
Here are practical examples showing how precedence affects expression evaluation −
<?php // Arithmetic precedence echo 10 + 5 * 2; // 20 (not 30) echo "<br>"; // Logical precedence $a = true; $b = false; echo $a && $b || $a; // 1 (true) echo "<br>"; // Assignment vs comparison $x = 5; $result = $x = 10; // Assignment has lower precedence echo $result; // 10 ?>
20 1 10
Conclusion
Understanding PHP operator precedence is crucial for writing predictable code. When in doubt, use parentheses to explicitly control the order of operations and make your code more readable.
