This forum is now read-only. Please use our new forums at discuss.codecademy.com.

For Loops in PHP Forum

View Course » View Exercise

165 points
59b90acd9e8471d26b000192_329479297
Submitted by
BassPlaya
over 4 years ago

Why would the first $i be echoed out?

Am I reading this wrongly?
Isn't the $i being updated before the end of the statement in the loop?

1st step: $i = 0;
2nd step: check wether $i is still smaller than 10; if it is go to step 3
3rd step: update the value of the variable $i by incrementing it with 1.

The result should then be: 123456789 instead of 0123456789, no?

Or is the initial setting of the variable $i a statement for the loop to know where to start?

"where to start the loop;"


1 vote

permalink

If you set $i =0 at the begining of the for-loop, the echo will print out the 0.
Maybe I can explain it to you by a while-loop:

$i =0;
while(i<10){
    echo $i;
    $i++; 
}

This is how a for-loop works, first it checks if the statement is true, if so it continues the code and after this, it increments the loop-variable.
I hope you got it
and sorry for my grammar ;>

563 points
Picture
Submitted by
Marv
over 4 years ago

1 Comment

574eb20c6eb9714a3e000359_387000418 Kannuki Wakaba over 4 years ago

That was very helpful. Thank you.