Use a for loop when you know how many times you want to repeat something.
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
1 2 3 4 5
The three parts
for (start; condition; step) { ... }
- Start (
$i = 1): runs once, before the loop. - Condition (
$i <= 5): checked before each round. The loop continues while it is true. - Step (
$i++): runs after each round.
It is the same logic as a while loop, but with the counter handling written in one line.
Counting down
<?php
for ($i = 5; $i >= 1; $i--) {
echo $i . " ";
}
echo "Lift off!";
5 4 3 2 1 Lift off!
Bigger steps
<?php
for ($i = 0; $i <= 20; $i += 5) {
echo $i . " ";
}
0 5 10 15 20
Sum of numbers
<?php
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i;
}
echo "Sum: $sum";
Sum: 55
Looping over array positions
You can use for with an array when you need the index. Compute count() once, so PHP does not do it every round.
<?php
$names = ["Ana", "Ben", "Cara"];
for ($i = 0, $total = count($names); $i < $total; $i++) {
echo ($i + 1) . ". " . $names[$i] . "\n";
}
1. Ana
2. Ben
3. Cara
If you do not need the index, foreach is simpler and safer.
Starting at 0 or 1
Array positions start at 0, so loops over arrays usually start at 0 and use < the length. Loops that count rounds for people usually start at 1 and use <=.
Off-by-one errors
$i <= count($arr) goes one step too far and reads a position that does not exist. For arrays, use $i < count($arr).Exercise: a times table
Print the 7 times table from 7 x 1 to 7 x 5, one per line, like 7 x 1 = 7.
Show a possible solution
<?php
for ($i = 1; $i <= 5; $i++) {
echo "7 x $i = " . (7 * $i) . "\n";
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35