Initial state:
$a = 0;
$x = $a+++(++$a);
When the post-increment operation of $a++
is evaluated, $a
still worth 0. We have at this time:
$x = 0 + (++$a);
$a = 1;
When evaluating the pre-increment operation of ++$a
, $a
is already worth 1. We have then:
$x = 0 + 2; // $x = 2
$a = 2;
Note that if you invert the expression the answer will still be 2, but the values of the expression change:
$a = 0;
$x = ++$a+$a++;
When the pre-increment operation of ++$a
is evaluated, $a
becomes worth 1. We have now:
$x = 1 + $a++;
$a = 1;
When the post-increment operation of $a++
is evaluated, $a
still worth 1. We have then:
$x = 1 + 1; // $x = 2
$a = 2;
Now an example with a larger expression. Why $a+++(++$a+$a+++(++$a))
is equal to 8?
Initial state:
$a = 0
$x = $a+++(++$a+$a+++(++$a));
When the first post-increment operation of $a++
is evaluated, $a
still worth 0. We have at this time:
$x = 0 + (++$a+$a+++(++$a));
$a = 1;
When the next pre-increment operation of ++$a
is evaluated, $a
is already worth 1. We have then:
$x = 0 + (2 + $a+++(++$a));
$a = 2;
When the next post-increment operation of $a++
is evaluated, $a
still worth 2. We have therefore:
$x = 0 + (2 + 2 + (++$a));
$a = 3;
When the next pre-increment operation of ++$a
is evaluated, $a
is already worth 3. We have at last:
$x = 0 + 2 + 2 + 4; // $x = 8
$a = 4;
1 + 1 = 2. No?
– Francisco
@Francis yes, but what happens in the syntax?
– Wallace Maxters
$a++
is the same thing as$a = $a + 1;
The(++$a)
also works the same way in this case. In that you add the two and the 2.– Francisco
Maybe something equally interesting
$a++-(++$a);
= 2, if analyzing the expression, 1 - 1 = 2 (?)– MarceloBoni
The manual itself has a very good explanation http://php.net/manual/en/language.operators.increment.php
– Marcos Xavier