PHP

The for statement

for loops are the most complex loops in PHP. They behave like their C counterparts.

Syntax:

for (expr1; expr2; expr3) {
    //statement;
}

The first expression (expr1) is evaluated (executed) once 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).

Example:

Following example displays 1 to 10.

<?php
for ($i = 1; $i <= 10; $i++) {
    echo $i.'<br />';
}
?>

Output:

Tutorialik.com
1
2
3
4
5
6
7
8
9
10

Each of the expressions can be empty or contain multiple expressions separated by commas.
In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part.
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.

Example:

<?php

$i = 1;
for (; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i.'<br />';
    $i++;
}
?>

Output:

Tutorialik.com
1
2
3
4
5
6
7
8
9
10

Example:

<?php

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}
?>

Output:

Tutorialik.com
1
2
3
4
5
6
7
8
9
10



Subscribe us on Youtube

Share This Page on


Ask Question