6

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.

Jall Oaan
  • 81
  • 6
  • Incrementing/Decrementing Operators: http://php.net/manual/en/language.operators.increment.php – solar411 Jan 13 '15 at 23:29
  • @solar411 can you reference something a little more specific? – scrowler Jan 13 '15 at 23:37
  • Here's a codepad for this: http://codepad.org/gEoWxshO. Very odd behaviour - it's like the pre-increment in the second block is executed again on the first `$piece` in the third block. Or maybe the post-increment in the third block is responsible, in which case, the inconsistency between the examples is not explained. – halfer Jan 13 '15 at 23:39
  • 1
    (The short answer is "don't write code like this", but it is an interesting question). – halfer Jan 13 '15 at 23:44
  • 2
    @halfer: This is essentially the PHP version of http://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior – Oliver Charlesworth Jan 13 '15 at 23:45
  • Just breaking this down a little more, even a simple `echo $piece . $piece++;` will output `11 10`. And a `echo $piece . ++$piece;` will output `11 11`. – Jonathan Kuhn Jan 13 '15 at 23:51

1 Answers1

6

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680