PHP Manualfor(PHP 4, PHP 5) 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) once unconditionally at the beginning of the loop.
In the beginning of each iteration,
expr2 is evaluated. If it evaluates to
At the end of each iteration, expr3 is evaluated (executed).
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
Consider the following examples. All of them display the numbers 1 through 10:
<?php 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. for (expr1; expr2; expr3): statement ... endfor; Its a common thing to many users to iterate though arrays like in the example below.
<?php The problem lies in the second for expression. This code can be slow because it has to calculate the size of the array on each iteration. Since the size never changes, it can be optimized easily using an intermediate variable to store the size and use in the loop instead of count. The example below illustrates this:
<?php
![]() |
PHP-Index
New Tutorial entries
|