Search code examples
phplogic

Confusing PHP Logic


So I got a PHP question in a paper. The question is to write the output of the given code.

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

So my answer was

5
12
5
0
5

This is what everyone wrote because it's the logically correct answer but when we practically implemented it the output was this.

5
11
7
1
5

Can someone explain to me how and why PHP would give this output? It's very confusing.


Solution

  • One thing you need to know is that $x++ uses the value, then increments it, while $x-- uses the value, the decrements it. So break down the code:

    $x = 5;  // Easy enough
    echo $x++ + $x++; // X is first 5. Use it, then increment it. X is now 6, use it, then increment it.  5+6 = 11
    echo $x; // Since we incremented it again on the previous line, x is now 7. 
    echo $x-- - $x--; // Use 7, decrement (x is now 6), subtract X, then decrement it. 7 - 6 = 1
    echo $x; //  X is now 5
    

    See https://www.php.net/manual/en/language.operators.increment.php , it has more information and examples on how it works.