Why does the pre / post increment statement behave incorrectly?

Why don't variable values ​​in PHP have consistent behavior in the following code?

<?php $piece = 10; // output is 10 10 10 10 11 12 echo $piece . $piece . $piece . $piece++ . $piece . ++$piece; $piece = 10; // output is 10 10 10 11 12 echo $piece . $piece . $piece++ . $piece . ++$piece; $piece = 10; // output is 11 10 11 12 echo $piece . $piece++ . $piece . ++$piece; ?> 

The question is why the first result in the last example is 11? instead of 10 since it gives more than 2 examples.

+6
source share
1 answer

From http://php.net/manual/en/language.operators.precedence.php :

Operator precedence and associativity only determine how expressions are grouped; they do not determine the order of evaluation. In PHP, it is not (in the general case) to indicate in what order the expression is evaluated, and code that involves a certain evaluation order should be avoided, because the behavior can vary between versions of PHP or depending on the surrounding code.

 <?php $a = 1; echo $a + $a++; // may print either 2 or 3 $i = 1; $array[$i] = $i++; // may set either index 1 or 2 ?> 
In other words, you cannot rely on a ++ action at a specific time relative to the rest of the expression.
+6
source

Source: https://habr.com/ru/post/980956/


All Articles