How to use a for loop in PHP 8

for loops are an essential building block in PHP 8 to iteratively execute a collection of statements. Its purpose is very versatile and ranges from array operations to scientific calculations.

A for loop consists of two parts: the control statement and the body of the loop. The control statement is a combination of three expressions which determine the start and end of the loop. The body of the loop contains the statements which should be executed in each iteration. Here is a small example:

for ($i = 0; $i < 10; $i = $i + 1) {
    echo $i . "\n";
}

0
1
2
3
4
5
6
7
8
9

Above you can see the result of the for loop.

Control statement

The control statements consist of 3 separate parts.

  1. An initial value for the loop: This is performed only once before the first iteration.
  2. A boolean expression: The expression is evaluated after each loop iteration. If it yields false, the loop won't continue.
  3. A statement for tracking the progress of the for loop.

All 3 parts are optional. So, a control statement without any instructions is sementically the same as a while loop checking for True

for (; ; ) {
    break;
}

while (true) {
    break;
}

For illustration purposes, here is a for loop with additional comments to indicate the execution location of the 3 parts of the control statement.

// $i = 0;
for ($i = 0; $i < 10 ; $i = $i + 1) {
    // if ($i < 10 == false) {
    //      break;
    // }
    break;
    // $i = $i + 1;
}

Body

As for the body, you can put any operations inside of the body. Additionally you have at your disposal special instruction keywords that allow you to skip ahead or cancel the loop. For jumping to the next iteration, you would use the instruction continue and for aborting the for loop the instruction break. They are handy if you wanted to iterate over an associative array to look for something. As soon as you have found the desired item, you'd stop the for loop to improve the performance of your program. You would use the continue instruction if you wanted to do an operation only on certain items that satisfy a condition. If they didn't satisfy the condition, you would use continue to skip ahead.