The for Construct

The for construct is used to organize loops with a known number of iterations. It consists of three parts: counter initialization, loop continuation condition, and counter modification on each iteration.

Syntax

phpfor (initialization; condition; increment) {
  // code to be executed
}

Example

Let's output numbers from 0 to 4:

php<?php
  for ($i = 0; $i < 5; $i++) {
    echo $i . ' ';
  }
?>

Code execution result:

php0 1 2 3 4

Example

Let's iterate through array elements:

php<?php
  $arr = ['a', 'b', 'c', 'd', 'e'];
  
  for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i] . ' ';
  }
?>

Code execution result:

phpa b c d e

Example

Let's output numbers from 10 to 1 in reverse order:

php<?php
  for ($i = 10; $i >= 1; $i--) {
    echo $i . ' ';
  }
?>

Code execution result:

php10 9 8 7 6 5 4 3 2 1

See Also

  • the while construct,
    which executes a loop while the condition is true
  • the foreach construct,
    which iterates over array elements