+ 3
Can anyone explain post and pre increment more better?
4 odpowiedzi
+ 3
ex1)$a = 2; $b = $a++; // $a=3, $b=2
(ex2)$a = 2; $b = ++$a; // $a=3, $b=3
in ex1, $b will just get the previous/original value of $a (which is 2), then assign new value to $a (becomes 3).
in ex2, $b will get the incremented value of $a, not the original value (2 becomes 3), then assign the new/incremented value which is now 3 to $a;
+ 2
why did the original value of $a in ex1 change? Tell me if i'm wrong. This is what i understand:
ex1) $a = 4 ; $b = $a++; // $a=5, $b=4
ex2) $a = 6 ; $b = ++$a; // $a=7, $b=7
+ 1
//POST INCREMENT
$x=1;$y=$x++; //x=2 and y=1
/*This is post increment because the value of x before increment will be inserted to y ($y=$x; //$x before increment x=1) first and the value of x will increase after inserting it value to y ($x++ ;//$x++ is equal to $x=$x+1)...*/
//PRE INCREMENT
$x=1;$y=++x; //x=2 and y=2
/*This is pre increment because the value of x will be increased first ($x++ ;//$x++ is equal to $x=$x+1) ...After that ,the value of x will be inserted to y($y=$x //$x after increment x=2)...*/
- 1
Good reply by Garizalde