steve
steve

Reputation: 586

Why does the post-increment operator ($j++) never change $j from 0?

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.

Upvotes: 2

Views: 1581

Answers (3)

Ned Batchelder
Ned Batchelder

Reputation: 375584

$j++ is post-increment: the value of the expression is $j, then $j is incremented. So you're getting the value of j, then incrementing j, then setting j to the original value of j.

Upvotes: 3

Marc B
Marc B

Reputation: 360682

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:

for ($i = 0; $i < 100; $i++) {
   $temp = $j;  // store j
   $j = $j + 1;  // $j++
   $j = $temp; // pull original j out of storage
}

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 out

 for (...) {
    $j++;
 }

which boils down to

for (...) {
   $j = $j + 1;
}

Upvotes: 6

Adam Liss
Adam Liss

Reputation: 48290

The problem is with the line

$j = $j++;

This command evaluates $j as 0, then increments $j to 1, and finally does the assignment of 0 back to $j.

Either use $j = $j + 1; or just $j++;.

Upvotes: 5

Related Questions