PHP 8.6.0 Beta 3 is available for testing

for

(PHP 4, PHP 5, PHP 7, PHP 8)

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.

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

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

<?php
for ($i = 1; $i <= 10; $i++) {
    echo $i . " ";
}

Il precedente esempio visualizzerà:

1 2 3 4 5 6 7 8 9 10
<?php
for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i . " ";
}

Il precedente esempio visualizzerà:

1 2 3 4 5 6 7 8 9 10
<?php
$i = 1;
for (; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i . " ";
    $i++;
}

Il precedente esempio visualizzerà:

1 2 3 4 5 6 7 8 9 10
<?php
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i . " ", $i++);

Il precedente esempio visualizzerà:

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 for loops comes in handy on many occasions.

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

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:

<?php

$people = ['Kalle', 'Pierre'];

// Bad practice: calling a function on every iteration
for($i = 0; $i < getIterationCount($people); ++$i) {
    $people[$i] .= ' is cool';
}

// Good practice: storing the count in a variable
for($i = 0, $peopleCount = getIterationCount($people); $i < $peopleCount; ++$i) {
    $people[$i] .= ' is cool';
}

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.

Nota:

The size of an array is stored with the array, which means that calling the built-in function count() does not require counting the elements and does not cause performance issues. This does not apply to COUNT_RECURSIVE, which walks the whole array. Care should also be taken when using count() on objects implementing Countable, as such calls can be more expensive.

Nota:

The for loop is not the recommended way to iterate over arrays. The foreach loop is specifically designed for this purpose and is usually more convenient.

add a note

User Contributed Notes 2 notes

up
340
matthiaz
14 years ago
Looping through letters is possible. I'm amazed at how few people know that.

for($col = 'R'; $col != 'AD'; $col++) {
    echo $col.' ';
}

returns: R S T U V W X Y Z AA AB AC

Take note that you can't use $col < 'AD'. It only works with !=
Very convenient when working with excel columns.
up
73
nzamani at cyberworldz dot de
25 years ago
The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops.
So you should try to take everything that doesn't change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:

<?php
for ($i = 0; $i <= somewhat_calcMax(); $i++) {
  somewhat_doSomethingWith($i);
}
?>

Faster would be:

<?php
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; $i++) {
  somewhat_doSomethingWith($i);
}
?>

And here a little trick:

<?php
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ;
?>

The $i gets changed after the copy for the function (post-increment).
To Top