Inspired by the issue of pre / post-increment . Code:

<?php $a=10; $a=$a++ + ++$a; echo $a; 

Ideone gives out 22, it was expected 23. Modification with prioritization $a=($a++) + (++$a); does not save. Question: Is the pre / post-increment behavior described in the PHP interpreter, or is this the classic undefined behavior?

Update: Yes, I confused the code for 23, there was exactly $a = ++$a + ++$a , here 22 without any questions, since the pre-increment is one. But the option $a= ++$a * (++$a + 2); turned out to be much more interesting - the answer to the Ideone 154! The second option, if it is first calculated (++$a +2) , 12 * 13 = 156. The question is valid - is the behavior of the PHP interpreter when calculating expressions with a pre / post-increment set, or different depending on the implementation?

  • Yeah. I can only assume that because of the left associativity (left to right execution) of the multiplication operator, the expression was calculated as follows: $a = (++$a) * (++$a + 2) . I can not confirm the document so far. - Alex Belyaev
  • @AlexBelyaev It seems that the correct answer is “first all pre / postincrements are calculated, and then the expression”, otherwise the second ++$a would be calculated first, and the answer would be 156. - Vesper
  • So it is obvious - we have already found out in fact that increments were calculated first. I in my commentary reasoned why they suddenly decided in this way to be considered. For example, I did not find anything about the comparative priority of brackets and increments in the docks. Maybe I looked bad :) - Alex Belyaev

2 answers 2

I do not understand why you expected 23 :) There is an official manual , where it is written in black and white that the prefix increment increases $ a by one, then returns the value of $ a. And the postfix increment returns the value of $ a, then increments $ a by one. The priority of operators is also described: increments before arithmetic operations (addition and subtraction, naturally after multiplication and division).

So:

 $a = $a++ + ++$a; // $a++ сначала возвращает 10, потом увеличивается ($a == 11) // ++$a сначала увеличивается ($a == 12), затем уже возвращается в выражение // 10 + 12 = 22 

Probably, I will say the obvious things, but in real life such non-obvious code should not be written. Please treat this as a workout for the mind. Although, in my opinion, it will be more useful to solve integrals :)

  • Few updated the question. Yes, I was wrong :) - Vesper
  • one
    Added in response a link to the priority of operators. I think undefined behavior was suspected in this particular moment. - Alex Belyaev

Typical code mindfak in action

I got off

 10+11 21+1 

why was expected 23 did not understand

pre-increment test cases

 $i = 5; $i = ++$i + ++$i; echo $i;//13 

and post

 $i = 5; $i = $i++ + $i++; echo $i;//11