PHP foreach Keyword
last modified November 25, 2026
The PHP foreach keyword walks an array or an object without an index. It assigns each element to a loop variable, optionally together with its key, and stops when the last element has been visited.
This article covers the value and key forms, iteration by reference and its pitfall, nested arrays, destructuring, break and continue, object properties, the alternative syntax, and the warning raised by a non-iterable value.
Basic definitions
foreach walks an array or an object and assigns each element to a loop variable. There are two forms: foreach ($array as $value) visits the values, and foreach ($array as $key => $value) visits the keys as well.
The value form works on a copy of each element, so assigning to $value does not change the array. Putting & before the variable makes it a reference to the element, and then assignments are written back. The loop variable and the key variable stay defined after the loop, and foreach does not move the array's internal pointer.
For an object, foreach visits the properties that are visible in the current scope: from outside the class, only public ones. Classes that implement Iterator or IteratorAggregate decide what iteration means for them. The iterators article covers that interface.
Iterating over values
The first example walks a list of colors. The same loop over an empty array runs zero times and raises no error.
<?php
declare(strict_types=1);
$colors = ['red', 'green', 'blue', 'yellow'];
foreach ($colors as $color) {
echo $color, " ";
}
echo "\n";
$empty = [];
foreach ($empty as $item) {
echo "never printed\n";
}
echo "done\n";
Each pass assigns the current value to $color, so the body can use it without an index. The order is the array's insertion order, not a sorted order. The empty array is a normal case in applications: a search may return no rows, and the loop simply does nothing before the code continues.
$ php foreach_values.php red green blue yellow done
Keys and values
The $key => $value form exposes the key. For an associative array the keys are the meaningful labels; for a list they are the indexes 0, 1, 2, and so on.
<?php
declare(strict_types=1);
$capitals = [
'France' => 'Paris',
'Germany' => 'Berlin',
'Italy' => 'Rome',
];
foreach ($capitals as $country => $capital) {
echo "The capital of $country is $capital\n";
}
$scores = [10, 20, 30];
foreach ($scores as $index => $score) {
echo "$index: $score\n";
}
The country names are the keys and the capitals are the values. PHP preserves the key type: the associative array keeps its strings, while the list keeps its integers. Both forms iterate in insertion order, and the second listing shows that the index is available even when it was never written in the literal.
$ php foreach_keys.php The capital of France is Paris The capital of Germany is Berlin The capital of Italy is Rome 0: 10 1: 20 2: 30
Modifying elements by reference
To change the array, iterate by reference. The ampersand must be written before the loop variable, and the reference has to be removed after the loop.
<?php
declare(strict_types=1);
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as &$number) {
$number *= 2;
}
unset($number);
print_r($numbers);
$names = ['alice', 'bob'];
foreach ($names as &$name) {
$name = ucfirst($name);
}
unset($name);
print_r($names);
Every pass writes through the reference, so the original array is doubled in place. unset($number) after the loop is not optional: without it, $number keeps pointing at the last element. The second loop applies the same pattern to strings with ucfirst, which returns a new string rather than changing its argument.
$ php foreach_reference.php
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
Array
(
[0] => Alice
[1] => Bob
)
The reference pitfall
A reference left over from an earlier loop is the classic foreach bug. The next example reuses the variable name in a second loop without unsetting it first.
<?php
declare(strict_types=1);
$a = [1, 2, 3];
foreach ($a as &$v) {
}
foreach ($a as $v) {
}
print_r($a);
echo "v=$v\n";
After the first loop $v is a reference to $a[2]. The second loop assigns each value to $v, so 1 lands in the last slot, then 2 lands there as well, and the third pass reads the value that the second pass just wrote. The array becomes [1, 2, 2], and $v is 2 at the end. Always unset a reference variable as soon as the loop that needed it is finished.
$ php foreach_pitfall.php
Array
(
[0] => 1
[1] => 2
[2] => 2
)
v=2
Nested arrays
An array element may itself be an array. Nested loops process each row and then each cell, or each group and then its members.
<?php
declare(strict_types=1);
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
foreach ($matrix as $row) {
foreach ($row as $cell) {
echo "$cell ";
}
echo "\n";
}
$teams = [
'alpha' => ['Alice', 'Bob'],
'beta' => ['Carol'],
];
foreach ($teams as $team => $members) {
echo "$team: ", implode(", ", $members), "\n";
}
The outer loop hands one row at a time to $row, and the inner loop walks that row. The newline after the inner loop starts a new line for each row. The second example shows the same pattern with string keys: each team name is the key and the member list is the value, so implode can turn the members into one line.
$ php foreach_nested.php 1 2 3 4 5 6 7 8 9 alpha: Alice, Bob beta: Carol
Destructuring elements
When every element is an array of the same shape, the loop header can unpack it. Square brackets around the variables replace a separate assignment inside the body.
<?php
declare(strict_types=1);
$rows = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
];
foreach ($rows as ['name' => $name, 'age' => $age]) {
echo "$name is $age years old\n";
}
$points = [[1, 2], [3, 4]];
foreach ($points as [$x, $y]) {
echo "($x, $y)\n";
}
The keyed form ['name' => $name, 'age' => $age] reads fields by name, which survives a change in their order. The short form [$x, $y] takes the values by position and suits indexed rows. A missing key raises an undefined array key warning and assigns null, so validate the shape of the data when it comes from outside the program. The array keyword article covers array literals and keys.
$ php foreach_destructure.php Alice is 30 years old Bob is 25 years old (1, 2) (3, 4)
break and continue
continue skips the rest of the current pass and moves to the next element. break ends the loop completely.
<?php
declare(strict_types=1);
$values = [10, 20, 30, 40, 50, 60];
foreach ($values as $value) {
if ($value === 30) {
continue;
}
if ($value === 50) {
break;
}
echo "$value ";
}
echo "\n";
30 is skipped by continue, and the loop stops at 50, so 60 is never visited. The output is 10, 20, and 40. The break statement and continue statement articles cover the level argument for nested loops.
$ php foreach_control.php 10 20 40
Object properties
Iterating an object visits its visible properties. Outside the class that means the public ones; private and protected properties are not part of the loop.
<?php
declare(strict_types=1);
class Book
{
public string $title = 'PHP Guide';
public string $author = 'Jane Doe';
private float $cost = 29.99;
}
$book = new Book();
foreach ($book as $property => $value) {
echo "$property: $value\n";
}
var_dump(get_object_vars($book));
The property names become keys and the property values become values, in declaration order. get_object_vars called from outside returns the same public set, which confirms that $cost was not visited. To expose a different sequence, implement IteratorAggregate and return a generator or an array iterator.
$ php foreach_object.php
title: PHP Guide
author: Jane Doe
array(2) {
["title"]=>
string(9) "PHP Guide"
["author"]=>
string(8) "Jane Doe"
}
Alternative syntax
The colon form replaces the braces and ends with endforeach. It is the usual choice in a template that mixes HTML and PHP.
<?php
declare(strict_types=1);
$fruits = ['apple', 'banana', 'cherry'];
?>
<ul>
<?php foreach ($fruits as $fruit): ?>
<li><?= htmlspecialchars($fruit) ?></li>
<?php endforeach; ?>
</ul>
The file closes the PHP tag, prints HTML, and reopens PHP for the loop. The short echo tag <?= prints each escaped value, and htmlspecialchars keeps the markup safe. The behavior is identical to the braced form; only the punctuation changes.
$ php foreach_alt.php
<ul>
<li>apple</li>
<li>banana</li>
<li>cherry</li>
</ul>
Non-array values
foreach accepts arrays and objects. Any other type raises a warning, the body is skipped, and the script continues.
<?php
declare(strict_types=1);
$value = 42;
var_dump(is_iterable($value));
foreach ($value as $item) {
echo $item;
}
echo "after\n";
is_iterable returns false for the integer, and the warning names the type it received. The final echo still runs, so a bad value degrades the output instead of stopping the page. Check with is_iterable before the loop, or declare an iterable parameter so the mistake is caught at the call site.
$ php foreach_nonarray.php bool(false) Warning: foreach() argument must be of type array|object, int given in /app/foreach_nonarray.php on line 9 after
Best practices
Most foreach bugs come from references and from changing the array while it is being walked.
Source
This article covered the PHP foreach loop: values, keys, references, nested data, destructuring, loop control, objects, and templates. Continue with PHP functions, or read PHP array keyword for the array type itself.
Author
List all PHP tutorials.