Using PHP 5.6, why does this code outputs
2
5
8
11
instead of
3
6
9
?
for ($i = 0; $i < 10; $i++) {
echo $i += 2 . "<br />";
}
Because i starts at 0, not 1. Lets see what is happening:
Loop 1
Initiate i, i = 0;
Check for loop condition ($i < 10). i is 0 so yes, run the loop.
Add 2 to i and echo. 0 + 2 = 2, echo 2.
End of loop, add 1 to i. i is 3.
Loop 2
Check for loop condition ($i < 10). i is 3 so yes, run the loop.
Add 2 to i and echo. 3 + 2 = 5, echo 5.
End of loop, add 1 to i. i is 6.
And so on. So you add 2, echo out then add 1.
You may be expecting the i++
in the for loop to run before the code, but it runs at the end of the code. From the PHP website:
At the end of each iteration,
expr3
is evaluated (executed).
If you want your output to be 3, 6, 9 then you would need to initiate i to 1 at the start of your loop.
for($i = 1; $i < 10; $i++)
The increment (i++
) in the loop header happens after the loop body is executed. So, i
is initialized to 0, then you add 2 and print it. Then, the loop header increments it to 3, then you add 2 and print it again...
In the first iteration, you add 0 + 2
, because you declared $i to be 0
, so the output would be 2. then with the $i++
you do the same as you would write $i += 1
. So now the value of $i
is 3.
Then you add again 2 which gives you 5 as an output, then you add another 1. Value of $i = 6, add 2... outputs 8... add 1... add 2... outputs 11...