PHP3 Manual
PrevChapter 6. Language constructsNext

FOR

FOR loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a FOR loop is:

    FOR (expr1; expr2; expr3) statement

The first expression (expr1) is evaluated (executed) unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional BREAK statement instead of using the FOR truth expression.

Consider the following examples. All of them display numbers from 1 to 10:

/* example 1 */
for ($i=1; $i<=10; $i++) {
    print $i;
}

/* example 2 */
for ($i = 1;;$i++) {
    if ($i > 10) {
        break;
    }
    print $i;
}

/* example 3 */
$i = 1;
for (;;) {
    if ($i > 10) {
        break;
    }
    print $i;
    $i++;
}

Of course, the first example appears to be the nicest one, but you may find that being able to use empty expressions in FOR loops comes in handy in many occasions.

There is only one format for FOR loops in PHP 3.

    FOR(expr): ... ENDFOR;  is NOT supported.


PrevHomeNext
DO..WHILEUpSWITCH