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.

6
  • Incrementing/Decrementing Operators: php.net/manual/en/language.operators.increment.php Commented Jan 13, 2015 at 23:29
  • @solar411 can you reference something a little more specific? Commented Jan 13, 2015 at 23:37
  • Here's a codepad for this: 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. Commented Jan 13, 2015 at 23:39
  • 1
    (The short answer is "don't write code like this", but it is an interesting question). Commented Jan 13, 2015 at 23:44
  • 2
    @halfer: This is essentially the PHP version of stackoverflow.com/questions/949433/… Commented Jan 13, 2015 at 23:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@OliverCharlesworth so i guess there is no logical explanation of this odd behavior... huh ?
@JallOaan: There is. You were assuming that it would evaluate in a particular order, but there is no basis for that assumption!
@OliverCharlesworth but it does evaluate in a particular order see 1st and 2nd example. Anyway Thanks.
@JallOaan: It doesn't; see the 3rd example!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.