Question:

What will be the output of the code below and why?

$x = 5;
echo $x;
echo "<br />";
echo $x+++$x++;
echo "<br />";
echo $x;
echo "<br />";
echo $x---$x--;
echo "<br />";
echo $x;

Answer:

The output will be as follows:

5
11
7
1
5

Here’s are the two key facts that explain why:

  1. The term $x++ says to use the current value of $x and then increment it. Similarly, the term $x-- says to use the current value of $x and then decrement it.
  2. The increment operator (++) has higher precedence then the sum operator (+) in order of operations.

With these points in mind, we can understand that $x+++$x++ is evaluated as follows: The first reference to $x is when its value is still 5 (i.e., before it is incremented) and the second reference to $x is then when its value is 6 (i.e., before it is again incremented), so the operation is 5 + 6 which yields 11. After this operation, the value of $x is 7 since it has been incremented twice.

Similarly, we can understand that $x---$x-- is evaluated as follows: The first reference to $x is when its value is still 7 (i.e., before it is decremented) and the second reference to $x is then when its value is 6 (i.e., before it is again decremented), so the operation is 7 - 6 which yields 1. After this operation, the value of $x is back to its original value of 5, since it has been incremented twice and then decremented twice.


Keywords:

© 2017 QuizBucket.org