Randy Smith
Randy Smith

Reputation: 92

Why does this output 19?

It is not clear the logic behind this PHP code to give out the answer 19. How can the answer be 19? What is the logic?

$i=5;
$i +=$i++ + ++$i;
echo $i;

Upvotes: 0

Views: 119

Answers (3)

$i += $i++ + ++$i ; 
$i = $i + ($i+1 + 1+$i);
19 = 7 + (5 + 7);

Upvotes: -1

Tim Groeneveld
Tim Groeneveld

Reputation: 9039

First, let's consider the following code:

<?php

$e = 0;
$e += ++$e;
echo $e;

Will the output be 2, or will it be 1?

One the second line, the right hand side of the equation ++$e; will increment the value of $e, making $e (temporarily) equal 1.

When the left hand side of the equation is run, $e equals 1 already, so 1 will be added the that value, so essentially, the line really says $e = 1 + 1.

<?php

$e = 0;
$e = 1 + 1;
echo $e;

When we do the same with the equation given earlier,

$i=5;
$i +=$i++ + ++$i;
echo $i;

The importance here is post and pre incrementing.

  • ++i increments i and evaluates to the new value of i.
  • i++ evaluates to the old value of i, and increments i.

When $i += $i++ + ++$i; is calculated, on the Right Hand Side, ++$i (which will be 5) and $i++ (which will be 7).

$i += 5 + 7 (which becomes 7 + 5 + 7) means that $i will equal 19.

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212472

$i=5;
$i +=$i++ + ++$i;
     ^
     Take value of $i as 5 then increment to 6
              ^
              increment value of $i from 6 to 7, and use the 7
          ^
          5 + 7 = 12
   ^ $i is already 7, because of the increments in the previous operations,
     so add the 12 we've just calculated, giving 19

Upvotes: 10

Related Questions