Jigsaw Posted December 31, 2016 Posted December 31, 2016 Hi, im learning PHP atm and I'm very confused about how increments work and am failing to make sense of this example that was given to me: e.g. $a = 2; $b = $a++; // $a=3, $b=2 $a = 2; $b = ++$a; // $a=3, $b=3 So "$b" is simply in other terms "$a+1"? And "$a" is 2, therefore $b is supposed to be 3 right? But it says its 2 instead? Could explain how this works pls Quote
SRB Posted January 2, 2017 Posted January 2, 2017 This was wrote with C in mind, but language is irrelevant for this question. http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i Outside of reading then, play with a few example loops. Quote
Jigsaw Posted January 3, 2017 Author Posted January 3, 2017 Thanks for the reply. I get the idea that ++i will increase the value of whatever "i" may be and then return/show the new value of "i" and i++ will increase the value of "i" but still keep the original value... Could you please provide me with an example where this might be used in mccodes (just to strengthen my understanding)? Quote
sniko Posted January 3, 2017 Posted January 3, 2017 (edited) I rarely come on here anymore... <?php $i = 1; // Assign the value (int) 1 to the variable. echo $i; // Output the value of the variable. echo PHP_EOL . PHP_EOL; $i = 1; // Assign the value (int) 1 to the variable. echo $i + 1; // Output the value of 1+1. echo PHP_EOL . PHP_EOL; $i = 1; // Assign the value (int) 1 to the variable. echo ++$i; // Increment the variable by 1, then output. echo PHP_EOL . PHP_EOL; $i = 1; // Assign the value (int) 1 to the variable. echo $i++; // Output the variable then increment by 1. https://eval.in/708535 Notice how the last output is 1 (when I guess you expect it to be 2), this is because of where the operator (++) is. If you then output $i after this line, the output will be 2. Edited January 3, 2017 by sniko Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.