Reputation: 81
Why the values of variable in PHP does not have a consistent behavior in 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 is the first output in the last example equal to 11? instead of 10 as it give in above 2 examples.
Upvotes: 6
Views: 107
Reputation: 272832
From http://php.net/manual/en/language.operators.precedence.php:
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change 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 the ++
taking effect at a particular time with respect to the rest of the expression.
Upvotes: 6