Reputation: 23
I have a question which I don't know the answer of. I've been thinking about it for a while.
The following code:
$i = 1;
while($i < 10)
if(($i++) % 2 == 0)
echo $i;
It correctly outputs 3579, but why isnt 1 also included in the output?
I'm a beginner with PHP and am looking forward for someone to help me.
Thank you very much! :D
Upvotes: 1
Views: 54
Reputation: 23958
Two modifications:
$i = 0; // Make it 0 from 1
while($i < 10)
if(($i++) % 2 == 0)
echo "<br/>".$i; // Make $i instead of $1
Output:
1
3
5
7
9
Program hand run:
1) Set $i to 0.
2) If it is greater than 10, go ahead.
3) Increment it by 1
4) So, for $i => 0->1, 1->2
4) if new $i is even, print it. (So for first loop iteration, you are have $i -> 1 instead of 0 because of ++$i
Upvotes: 3