the result of the following statement should give 9 : (using java or js or c++)
i = 1;
i += ++i + i++ + ++i;
//i = 9 now
but in php
the same statements will give 12 ?!
$i = 1;
$i += ++$i + $i++ + ++$i;
echo $i;
is this a bug or can anyone explain why ?
Pre-increment. Increments $a by one, then returns $a . $a++ Post-increment. Returns $a , then increments $a by one.
Save this answer. Show activity on this post. ++$i is pre-increment whilst $i++ post-increment. pre-increment: increment variable i first and then de-reference.
There is no difference between ++$j and $j++ unless the value of $j is being tested, assigned to another variable, or passed as a parameter to a function.
In Pre-Increment, the operator sign (++) comes before the variable. It increments the value of a variable before assigning it to another variable. In Post-Increment, the operator sign (++) comes after the variable. It assigns the value of a variable to another variable and then increments its value.
The answer is "because it's PHP". And PHP doesn't make guarantees about that type of statement (incidentally, neither does C).
Yes, it could be considered wrong, but it's PHP. See this "not a bug" bug report.
Look here for a similar example.
Basically this is what happens:
First ++$i
is evaluated. $i
is now 2.$i += 2 + $i++ + ++$i;
Next, $i++
is evaluated. $i
is now 3.$i += 2 + 2 + ++$i;
Next, ++$i
is evaluated. $i
is now 4.$i += 2 + 2 + 4;
Lastly the sum is computed:$i = 4 + 2 + 2 + 4 = 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With