PHP Foreach Loops
foreach iterates arrays and any object that implements Traversable. It's the idiomatic way to walk a collection in PHP.
Values only
PHP
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
echo $fruit, PHP_EOL;
}
Key + value
PHP
$ages = ['Ada' => 36, 'Grace' => 56, 'Linus' => 42];
foreach ($ages as $name => $age) {
echo "$name is $age", PHP_EOL;
}
Modifying during iteration
Iterate by reference to mutate items in place:
PHP
$nums = [1, 2, 3];
foreach ($nums as &$n) { // & = reference
$n *= 2;
}
unset($n); // important — break the reference
print_r($nums); // [2, 4, 6]
Destructuring values
PHP
$points = [[1, 2], [3, 4], [5, 6]];
foreach ($points as [$x, $y]) {
echo "($x, $y) ", PHP_EOL;
}
Template syntax
PHP
<ul>
<?php foreach ($items as $item): ?>
<li><?= htmlspecialchars($item) ?></li>
<?php endforeach; ?>
</ul>
Tip: If you use
&$value to iterate by reference, always unset($value) right after the loop — the reference outlives the loop and biting the next assignment is a classic bug.Example
Example
<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $i => $f) {
echo "$i: $f", PHP_EOL;
}
Try it Yourself »
Exercise
Iterate key + value with this form.
foreach ($ages as $name
$age) {}
Two characters; an arrow.
Discussion
Loading…