Home >Backend Development >PHP Problem >What is the precedence of operators in php?
Operator precedence specifies how "tightly" two expressions are bound. For example, the expression 1 5 * 3 evaluates to 16 instead of 18 because the multiplication sign ("*") has higher precedence than the plus sign (" "). Parentheses can be used to force a priority change if necessary. For example: (1 5) * 3 has the value 18.
The operator priority determines the order of operations. The one with higher operation level is calculated first. If the priorities are the same, the combination direction of the operators determines how to operate. Priority changes can be forced by using parentheses.
The order of operator precedence from high to low is as follows:
Combining direction | Operator | Additional information |
---|---|---|
None | clone new | clone and new |
left | [ | array() |
right | — ~ (int) (float) (string ) (array) (object) (bool) @ | Type and increment/decrement |
None | instanceof | Type |
Right | ! | Logical operator |
Left | * / % | Arithmetic operators |
– . | Arithmetic operators and string operators | |
10e3fdaca48eb0367c6d60dbc98f885d> | Bitwise operator | |
= = != === !== a8093152e673feb7aba1828c43532094 | Comparison operator | |
& | bit operation Symbols and references | |
^ | bit operators | |
| | Bitwise operators | |
&& | Logical operators | |
|| | Logical operator | |
? : | Ternary operation Symbol | |
= = -= *= /= .= %= &= |= ^= 639513f5eb9d8dcbce09d6b5cb44cf73>= => ; | Assignment operator | |
and | Logical operator | |
xor | logical operator | |
or | logical operator | |
, |
Example: Combining Directions
<?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 ?>
Note: Using parentheses, even when not strictly required, often enhances the readability of your code.
Although
= has lower precedence than most other operators, PHP still allows expressions like the following: if (!$a = foo()), in this case The return value of foo() is assigned to $a.
The above is the detailed content of What is the precedence of operators in php?. For more information, please follow other related articles on the PHP Chinese website!