Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading