PHP For Loop

A for loop repeats code a known number of times using a single line that bundles together the counter setup, the stop condition, and the counter update.

The three parts of a for loop

The for loop is the tool of choice when you know how many times you want to repeat something. Its header packs three expressions into one line, separated by semicolons. The first sets up a counter, the second is the condition checked before each pass, and the third updates the counter after each pass. Keeping all three in one place makes counting loops easy to read.

PartRuns whenPurpose
InitializationOnce, at the startCreate and set the counter
ConditionBefore every passDecide whether to continue
UpdateAfter every passMove the counter forward

Counting from 1 to 5

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Row $i\n";
}
?>

Here $i starts at 1, the loop continues while $i is 5 or less, and $i grows by one after each pass. The result is five lines of output. The variable name $i is a long-standing convention for a loop counter, short for 'index', though you may use any valid variable name.

Counting in different steps

The update expression does not have to add one. You can count in larger steps, or count downward. The example below counts backwards from 10 to 0 in steps of two, which shows how flexible the for header can be.

Counting down by twos

<?php
for ($n = 10; $n >= 0; $n = $n - 2) {
    echo "$n ";
}
echo "\nLift off!\n";
?>
Note: A for loop is often used to walk through an indexed array by its position. Use count($array) to get the length, and loop while your index is less than that length.

Walking an array by index

<?php
$colors = ["red", "green", "blue"];
for ($i = 0; $i < count($colors); $i++) {
    echo "Color at position $i is $colors[$i]\n";
}
?>
  • Choose for when the number of passes is known or can be calculated.
  • Array indexes start at 0, so loop from 0 up to but not including the length.
  • The condition uses less-than with count() to stay inside the array bounds.
  • For simply visiting each element, the foreach loop on the next page is usually cleaner.
Note: Avoid changing the counter inside the loop body in ways the header does not expect. Mixing two sources of updates makes the loop hard to follow and is a frequent cause of off-by-one bugs.