Increment Question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Increment Question

<?php $x = 2; $y = $x++; echo $y; ?> Why the result is 2. x = 2, and when x ++ that Means should be 2 + 1. And the result is 3. But why 2?

10th Mar 2017, 1:31 PM
Zainal Mubarok
Zainal Mubarok - avatar
6 Answers
+ 2
$y = $x++; is equal to $y = $x; $x = $x + 1; $y = ++$x; is equal to $x = $x + 1; $y = $x;
10th Mar 2017, 1:49 PM
AtoMX
AtoMX - avatar
+ 2
there is a lot of diff between x++ and ++x . x++ means post incrementation, hence value of x++ remains same as that of x,and x is incremented later on.
10th Mar 2017, 1:49 PM
Meharban Singh
Meharban Singh - avatar
+ 1
$y = $x++; set current value of $x (2) to $y then increment $x to 3 obtain 3 with $y = ++$x;
10th Mar 2017, 1:35 PM
AtoMX
AtoMX - avatar
+ 1
yes
10th Mar 2017, 1:46 PM
AtoMX
AtoMX - avatar
+ 1
$y = $x++ means that you assign the value of $x (2) to $y and THEN you increase the $x value from 2 to 3. That's why echo $y is 2, not 3.
10th Mar 2017, 1:57 PM
Jiří Vlach
Jiří Vlach - avatar
0
so, if i answer 3, this is value of $x?
10th Mar 2017, 1:45 PM
Zainal Mubarok
Zainal Mubarok - avatar