The PHP operator precedence refers to when doing a calculation for three or more numbers, they are calculating its values according to the priority. For example, 10 + 10 × 2, the result is 30 and not 40. That will lead us to explain the reasons in the following sections.
The PHP operator precedence, like in the below down table.
|** – / %||Arithmetic|
|++ —||Increment and Decrement|
|( ! – || – && – or – xor – and )||The Logical Operators|
|*/||Multiplication and Division|
|+ – .||Arithmetic and String|
|( | – ^ – & – << >> )||Bitwise|
|== != === !== <> <=>||Comparison Operator|
|new clone||new and clone objects|
|yield from||yield from|
The following section shows you examples for the PHP operator precedence.
<?php $calcs = 10 + 20 * 5; echo $calcs; // 110 ?>
In the previous example, the highest precedence was for the multiplication, So it was written behind the scenes like this: (20 × 5) = 100 and add 10, so it would 110.
Also, check the multiplication with the modulo operator. You will see the same highest precedence for multiplication.
<?php $calcs = 20 * 3 % 50; echo $calcs; // 10 ?>
So, it has written as the 20 * 3 = 60. And then the modulo operator is added to the result as the 60 % 50. So the result was 10.
Anyway, in the following example, you will see another kind of PHP operator precedence with the PHP variable assignment.
Use PHP Operator Precedence with Assignment
<?php $x = 10; $f = &$x; $y = 20; $x = $y += 5; echo $f; echo "\n"; echo $y; echo "\n"; echo $x; ?>
The result of this example would be like the following.
25 25 25
The three variables produced the same value. Let’s demonstrate each one.
The first printed variable
echo $f was 25 and not 10. That is because it has a reference operator, it will remain for the last value for the
&$x variable. So the last value for the
$x was 25.
On the other hand, the $y is produced 25 also because we added +5 in the last variable
$x = $y += 5;. So the old one was 20 and added +5 to be 25.
And in the final one, it produced a result of 25 because it assigned the $y variable and the $y variable also produced 25 for the previous reason.
Anyway, PHP operator precedence also can be returning undefined values with assigned arithmetic. So the potential result for the calculation is two results. Which are called undefined order of evaluation. Let’s see an example.
<?php $x = 10; echo $x + $x++; // it may print 21 or 20 ?>
In the next example, there are two values for a boolean data type. The priority would be for the positive one. Let’s take an example.
<?php var_dump( true || false ); // bool(true) ?>
Also, if it is with AND operator, it will show you false as a boolean result.
<?php var_dump( true && false ); // bool(false ) ?>
Thank you for reading.