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.
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";
?>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.