Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Oct 21 Previous

1 + 1 on steroids

Consider the following two lines of code. What will it display in your browser?

$i = 1;
echo $i++ + ++$i;

A: 2
B: 3
C: 4
D: 5


Obviously this is a very bad piece of code but nevertheless let's take a good look at it. On line tree we'll find a post-increment, an addition and a pre-increment. Now how are the executed?

The operands of the addition are evaluated from left to right and the increment operation has a higher precedence than the addition operator. This means that $i++ will be evaluated first and what happens there is that because of the post-increment the value of 1 will be set aside for the addition and then $i is incremented.

Then the right side (++$i) of the addition operand will be evaluated. $i now has the value of 2 and because this is a pre-increment the value will be incremented to 3 before it is set apart for the addition.

So at the time the addition itself is evaluated its left operand has the value of 1 and the right one has the value of 3. So 4 (answer C) will be echoed to your browser.