PHP Manual
Prev | Chapter 11. Control Structures | Next

# `for`

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

      1
      2 for (expr1; expr2; expr3) statement
      3

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).

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:

      1
      2 /* example 1 */
      3
      4 for ($i = 1; $i <= 10; $i++) {
      5     print $i;
      6 }
      7
      8 /* example 2 */
      9
     10 for ($i = 1;;$i++) {
     11     if ($i > 10) {
     12         break;
     13     }
     14     print $i;
     15 }
     16
     17 /* example 3 */
     18
     19 $i = 1;
     20 for (;;) {
     21     if ($i > 10) {
     22         break;
     23     }
     24     print $i;
     25     $i++;
     26 }
     27
     28 /* example 4 */
     29
     30 for ($i = 1; $i <= 10; print $i, $i++) ;
     31

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in `for` loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for `for` loops.

      1
      2 for (expr1; expr2; expr3): statement; ...; endfor;
      3

Other languages have a `foreach` statement to traverse an array or hash. PHP3 has no such construct; PHP4 does (see foreach). In PHP3, you can combine while with the list() and each() functions to achieve the same effect. See the documentation for these functions for an example.

Prev | Home | Next
`do..while` | Up | `foreach`