It seems like the following from the PHP manual regarding for
loops is incorrect.
They behave like their C counterparts.
This is my understanding of for
loops.
In Cfor (i = foo; i < 10; i++) { /* body */ }
is equivalent to
if ( i = foo )
{ while (i < 10)
{ /* body */
i++;
}
}
In PHP the comparable loopfor ($i = $foo; $i < 10; $i++) { /* body */ }
becomes
$i = $foo;
while ($i < 10)
{ /* body */
$i++;
}
The difference is that in PHP $i = $foo
is not a condition but rather a convenient place for a statement. Suppose we change the single =
to ==
. The distinction becomes significant. Is this correct? If so, then PHP and C loops behave differently and the manual is incorrect, right?
They are exactly the same, but your understanding of C's for
loops is wrong. They are the same as in PHP.
for (x; y; z) { /* body */ }
is almost like
x;
while (y) {
/* body */
z;
}
Though the for
and while
examples in C are not exactly the same because of scopes and things.
This is not true:
if ( i = foo ) //what??
{ while (i < 10)
{ /* body */
i++;
}
}
The C for loop is basically:
int i = foo;
while (i < 10)
{ /* body */
i++;
}
It's been a while since I learned or spend time with C, but I'm pretty sure the first statement in a C for-loop is an expression setting a variable to a value, just like it is in C.
In C i=foo
is indeed a condition, it's equivalent to (i=foo)!=0
since 0
is false
in C and not-0
is true
.
The issue is that C for
loops don't work the way you think they do, as evidenced by the fact that you can initialize a for loop with i=0
.