for
for (expr1; expr2; expr3)
statement
The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.
At 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: The above example will output: 1 2 3 4 5 6 7 8 9 10 The above example will output: 1 2 3 4 5 6 7 8 9 10 The above example will output: 1 2 3 4 5 6 7 8 9 10 The above example will output: 1 2 3 4 5 6 7 8 9 10
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
PHP also supports the alternate "colon syntax" for
for (expr1; expr2; expr3):
statement
...
endfor;
Expressions expr2 and expr3 are evaluated every iteration. It's advisable to use simple expressions in these places to avoid performance issues. For example, if the number of iterations is known in advance, it is better to use a variable instead of a function call in expr2:
In the example above, the function is called on every iteration of the first loop, even though it always returns the same value. Storing that value in a variable, as the second loop does, calls the function once. Note that the number of iterations is then fixed: if the array is modified inside the loop, the stored value no longer reflects its size.
|