PHP For & Foreach Loops
When you know how many times to repeat something, or you want to visit every element of an array, PHP gives you two specialised loops: for (a counting loop) and foreach (an array walker). In everyday PHP, foreach is by far the most used loop of all.
The for loop
for (init; condition; step) {
// body
}- init runs once before the loop starts (usually
$i = 0). - condition is checked before every pass; the loop stops when it is false.
- step runs after every pass (usually
$i++).
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Lap $i\n";
}Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
The step can be anything — count down, or move in bigger jumps:
<?php
echo "Even numbers: ";
for ($n = 0; $n <= 10; $n += 2) {
echo $n, " ";
}
echo "\n";
echo "Countdown: ";
for ($n = 3; $n >= 1; $n--) {
echo $n, " ";
}
echo "\n";
// A small multiplication table with nested loops
for ($row = 1; $row <= 3; $row++) {
for ($col = 1; $col <= 4; $col++) {
echo str_pad($row * $col, 4, " ", STR_PAD_LEFT);
}
echo "\n";
}Even numbers: 0 2 4 6 8 10
Countdown: 3 2 1
1 2 3 4
2 4 6 8
3 6 9 12
Tip: When looping over an array with
for, computecount($arr)once before the loop (for ($i = 0, $n = count($arr); $i < $n; $i++)) instead of calling it on every pass. Better yet, useforeach.
The foreach loop
foreach visits each element of an array (or any iterable object) in order. There are two forms:
foreach ($array as $value) { ... }
foreach ($array as $key => $value) { ... }<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo "I like $fruit\n";
}
$prices = ["coffee" => 3.5, "tea" => 2.75, "juice" => 4.0];
foreach ($prices as $item => $price) {
printf("%-6s costs %.2f\n", $item, $price);
}
foreach ($fruits as $index => $fruit) {
echo "#$index: $fruit\n";
}I like apple
I like banana
I like cherry
coffee costs 3.50
tea costs 2.75
juice costs 4.00
#0: apple
#1: banana
#2: cherry
No counter, no count(), no risk of an off-by-one error. With indexed arrays the key is the position, with associative arrays it is the string key.
Changing values: by reference
The loop variable is normally a copy, so assigning to it does not change the array. Put & in front of it to get a reference to the real element. Always unset() the reference afterwards — it keeps pointing at the last element and can cause strange bugs if you reuse the variable later.
<?php
$scores = [70, 85, 90];
foreach ($scores as $s) {
$s += 5; // changes only the copy
}
echo "Copy loop: ", implode(", ", $scores), "\n";
foreach ($scores as &$s) {
$s += 5; // changes the array element
}
unset($s); // break the reference
echo "Reference loop: ", implode(", ", $scores), "\n";Copy loop: 70, 85, 90
Reference loop: 75, 90, 95
An alternative that avoids references entirely is to write through the key: foreach ($scores as $k => $s) { $scores[$k] = $s + 5; }.
Destructuring in foreach
When each element is itself an array, you can unpack it directly in the loop header with [...] (or list(...)):
<?php
$orders = [
["Pen", 3, 1.20],
["Notebook", 2, 4.50],
["Ruler", 1, 0.99],
];
$total = 0;
foreach ($orders as [$product, $qty, $unit]) {
$line = $qty * $unit;
$total += $line;
printf("%-9s x%d = %5.2f\n", $product, $qty, $line);
}
printf("Total = %5.2f\n", $total);Pen x3 = 3.60
Notebook x2 = 9.00
Ruler x1 = 0.99
Total = 13.59
Which loop should I use?
| Situation | Loop |
|---|---|
| Visit every element of an array | foreach |
| Repeat a fixed number of times / numeric ranges | for |
| Repeat until a condition changes | while |
| Must run at least once | do...while |
Test yourself
How many times does for ($i = 0; $i < 10; $i += 3) run its body?
- 3
- 4
- 10
- 9
Which foreach gives you both the key and the value?
foreach ($a as $v => $k)foreach ($a as $k => $v)foreach ($k, $v in $a)foreach ($a : $k, $v)
Why should you unset($v) after foreach ($arr as &$v)?
- To free the array
- Because
$vis still a reference to the last element - PHP requires it or the code fails
- To reset the array pointer