I’ve encountered a strange problem with the increment operator. What should the code below output?
$j = 0;
for ($i=0; $i<100; $i++)
{
$j = $j++;
}
echo $j;
It echoes 0. Why not 100?
Edit: When I change $j = $j++ to $j = ++$j, it echoes 100.
You’re doing a “post-increment”, since the
++appears AFTER the variable it’s modifying. The code, written out in less compact form, boils down to:If you had
++$j, then j would increment FIRST, and the resulting incremented value would be assigned back to J. However, such a structure makes very little sense. you can simply write outwhich boils down to