Reputation: 881
I came along this script lately:
$i = 0;
$x = $i++; $y = ++$i;
print $x; print $y;
The output was 02
. I can imagine that you can't count +1 on $i
with ++
while it is 0, but why does $y
output as 2? And why isn't the output 11
or 01
?
Upvotes: 1
Views: 191
Reputation: 15301
post increment vs pre increment.
Post: Trailing $i++
means that $i
is returned and then incremented after.
Pre: Preceding ++$i
means that $i
is incremented and that result is returned.
So $x
is set to 0
(the initial value of $i
) and then incremented. $i
is now equal to 1
. Then $i
is incremented again to 2
and that value is set in $y
. So in the end, $x=0
and $y=2
and $i=2
. Your code could be rewritten as:
$i=0;
//x, post increment, set x to i then increment after.
$x=$i;
$i=$i+1;
//y, pre increment, increment first and then set y to i.
$i=$i+1;
$y=$i;
Same thing applies to the decrement operator --$i
and $i--
.
Upvotes: 2