The operator precedence specifies how tightly the two expressions are bound. For example, the result of an expression 1 + 5 * 3 is 16 instead of 18 because multiplication sign ("*") has a higher precedence than a plus sign ("+"). You can use parentheses to force a change of precedence if necessary. For example: (1 + 5) * 3 has a value of 18.
If the operator has the same precedence, its binding direction determines whether the value should be evaluated from right to left or left to right-see the following example.
The following table lists the operators by priority from high to low. Operators in the same row have the same precedence, at which point their binding direction determines the order of evaluation.
Operator precedence is shown in the following table
Operator Precedence
Combination Direction |
operator |
Additional Information |
No |
Clone new |
Clone and New |
Left |
[ |
Array () |
Right |
+ +--~ (int) (float) (string) (array) (object) (BOOL) @ |
Type and increment/decrement |
No |
instanceof |
Type |
Right |
! |
logical operators |
Left |
* / % |
Arithmetic operators |
Left |
+ - . |
Arithmetic operators and string operators |
Left |
<< >> |
Bitwise operators |
No |
= = = = = = =!== <> |
Comparison operators |
Left |
& |
Bitwise operators and references |
Left |
^ |
Bitwise operators |
Left |
| |
Bitwise operators |
Left |
&& |
logical operators |
Left |
|| |
logical operators |
Left |
? : |
Ternary operators |
Right |
= + = = *=/=. =%= &= |= ^= <<= >>= = |
Assignment operators |
Left |
and |
logical operators |
Left |
Xor |
logical operators |
Left |
Or |
logical operators |
Left |
, |
Used in many places |
For operators with the same precedence, the left-associative direction means that the left-to-right value is evaluated and the right-bound direction is the opposite. For operators with the same precedence in a no-union direction, the operator may not be able to combine with itself. For example, in PHP 1 < 2 > 1 is an illegal statement, and 1 <= 1 = = 1 is not. Because the t_is_equal operator has a lower precedence than the t_is_smaller_or_equal operator.
Example #1 Combination Direction
<?php$a = 3 * 3 5; (3 * 3)% 5 = 4$a = true ? 0 : true ? 1 : 2; (true? 0:true)? 1:2 = 2$a = 1; $b = 2; $a = $b + = 3; $a = ($b + = 3) $a = 5, $b = 5//Mixing + + + produces undefined behavior$a = 1; echo + + $a +
$a + +; May print 4 or 5?>
The use of parentheses can often enhance the readability of your code, even when it is not strictly required.
Note:
Although = is lower than most other operators, PHP still allows an expression similar to the following: if (! $a = foo ()), in this case the return value of foo () is assigned to the $a.