PHP operator priority
PHP operator priority describes the order in which operations are performed when the computer calculates expressions. . Operations with higher priority are performed first, followed by operations with lower priority. For example, we often say that multiplication and division are performed first, and then addition and subtraction are performed.
Order of php operator precedence
The following table lists the precedence of operators from high to low. Operators in the same line have the same precedence, and the precedence of operators is evaluated from left to right in the expression.
Priority | Combining direction | Operator | Additional information |
---|---|---|---|
1 | non-binding | clone new |
clone and new |
2 | left | [ |
array() |
3 | Non-associative | -- |
Increment/decrement operator |
4 | Non-associative | ~-(int)(float)(string)(array)(object)(bool)@ |
Type |
5 | Non-associative | instanceof |
Type |
6 | Right combination | ! |
Logical operator |
7 | Left | */ %
|
Arithmetic operator |
8 | left | -. |
Arithmetic operators and string operators |
9 | left | <<&gt ;> |
Bitwise operators |
10 | Non-associative | <<= >>=<> |
Comparison operator |
11 | Non-associative | ==!====!== |
Comparison operator |
12 | left | & |
Bitwise Operators and References |
13 | left |
^ |
Bitwise operators |
14 | left | | |
Bitwise operations Symbol |
15 | left | && |
Logical operator |
16 | left | || |
Logical operator |
17 | left | ?: |
ternary operator |
18 | right | = =-=*=/= .= %= &= |= ^= <<= >>= |
Assignment Operator |
19 | left | and |
logical operator |
20 | left | xor |
logical operator |
21 | left | or |
logical operator |
22 | left | , |
is used in many places to illustrate that
pairs have the same For precedence operators, the left associative direction means that the evaluation will be from left to right, and the right associative direction means the opposite. It is possible that an operator with the same precedence without associative direction cannot be combined with itself.
For example, in PHP 1 < 2 > 1 is an illegal statement, but 1 <= 1 == 1 is not. Because <= has higher priority than ==.
<?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 ++ and + produces undefined behavior $a = 1; echo ++$a + $a++; // may print 4 or 5 ?>
So under the premise that we are very clear about the priority of PHP operations, it is best to use parentheses to mark the priority when writing operators. This is more readable and is also a good programming Habit.
For more PHP related knowledge, please visit php中文网!
The above is the detailed content of What is the precedence of php operators?. For more information, please follow other related articles on the PHP Chinese website!