Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 147 ยท Control Flow

foreach Loops

Learn the PHP foreach loop - values and keys, nested arrays, modifying elements, the by-reference dangling-reference bug, destructuring rows and iterating objects.

Most of the data a PHP program handles comes in arrays: rows from a database, fields from a form, items in a cart, lines of a file. The foreach loop is made for exactly this. It visits each element of an array once, in order, and hands it to you, with no counters, no index arithmetic and no way to run past the end.

This lesson covers everything foreach can do: reading values and keys, working with nested arrays, changing elements (and the by-reference bug that catches almost every PHP developer once), unpacking rows with destructuring, and looping over objects. You'll see arrays in many shapes here; they get a full chapter of their own starting with Arrays. If you haven't read while, do-while and for Loops yet, it's a good primer on loops in general.

Looping over values

The basic form names the array and a variable that receives each element in turn:

PHP
foreach ($array as $value) {
    // $value is the current element
}
PHP Visiting every element

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The loop variable name is up to you; a singular noun for a plural array ($language in $languages) reads naturally. An empty array runs the body zero times, which is usually exactly right and needs no special check.

Keys and values

Every PHP array element has a key. Lists have the keys 0, 1, 2โ€ฆ, and associative arrays have keys you choose. Add $key => to receive the key too:

PHP
foreach ($array as $key => $value) {
    // $key is the current key, $value its element
}
PHP Reading keys and values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last loop shows an important detail: foreach visits elements in the order they were added to the array, not sorted by key. If you need a different order, sort the array first (see Sorting Arrays).

Nested arrays

Real data is often an array of arrays, such as a list of records where each record is an associative array. Loop over the outer array and read fields from each inner one, or nest a second foreach when the inner arrays are lists too:

PHP Records and nested lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Inside a double-quoted string, array elements with string keys need curly braces: "{$order['id']}". The rules are in Strings. Deeper structures and functions like array_column() are covered in Multidimensional Arrays.

Changing elements while looping

Here is a surprise for many beginners: assigning to the loop variable does not change the array. foreach gives you a copy of each value:

PHP The loop variable is a copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Writing through the key works with any array. Building a new array is often even better, because the original stays intact, and it's exactly what array_map() does in one line (see array_map, array_filter and array_reduce).

Also note that a by-value foreach loops over the array as it was when the loop started. If the body adds elements to the same array, the loop won't visit them, so it can't run forever by appending.

By reference: &$value

The third option is to iterate by reference. Put & before the loop variable, and $value becomes another name for the actual element, so assigning to it changes the array:

PHP
foreach ($prices as &$price) {
    $price *= 2;     // changes the element itself
}
unset($price);       // essential, see below

That unset() line isn't decoration. After the loop ends, $price is still a reference to the last element of the array. If you later reuse the same variable name in another loop, every assignment to it writes into that last element. This is one of PHP's most famous bugs:

PHP The dangling reference bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The array ends as RED, GREEN, GREEN: the last element was overwritten. During the second loop, each iteration assigns the current element to $color, which is a reference to $colors[2]. So $colors[2] becomes RED, then GREEN, then (when the loop reaches it) its own current value, GREEN. No warning, no error, just wrong data.

The fix is one line. Unset the reference right after the loop, which removes the name without touching the element:

PHP Unsetting the reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Warning: Every by-reference foreach should be followed immediately by unset() of its loop variable. Many teams avoid &$value loops entirely and write through the key or build a new array instead, because those can't leave a reference behind.

References in general (what they are and when PHP copies arrays) come up again in Variables and Parameters and Arguments.

Destructuring in foreach

When each element is itself an array, you can unpack it straight into variables in the loop header. Square brackets on the left side of as work like [$a, $b] = $pair;:

PHP Unpacking rows in the loop header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The keyed form ['email' => $email] pulls out only the fields you need, which is perfect for database rows. In older code you'll see the same thing written with list(): foreach ($results as list($name, $score)). The bracket syntax (PHP 7.1) is shorter and does the same. Destructuring has more tricks, like skipping elements and nested patterns, covered in Destructuring and Spread.

Iterating objects

foreach also works on objects. For an ordinary object, it visits the properties you're allowed to see from where the loop runs: public properties from outside the class, all properties from inside it:

PHP Looping over object properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The private $supplierCode is hidden from the outside loop, which respects the same visibility rules as $lamp->supplierCode would (see Classes, Properties and Methods). The last loop uses ArrayIterator, one of PHP's built-in classes that implement the Traversable interface. Such objects decide for themselves what foreach sees, which is how database results, file readers and Generators can be looped over like arrays. Iterators and the SPL shows how to write your own.

What foreach can't loop over

foreach accepts only arrays and objects. Give it anything else, typically null from a function that found nothing, and PHP prints a warning and skips the loop:

TEXT
Warning: foreach() argument must be of type array|object, null given in main.php on line 3

The best fix is upstream: make functions return an empty array instead of null when there's nothing to return. When you can't control the source, foreach ($items ?? [] as $item) falls back to an empty array (see Null Coalescing, Ternary and Nullsafe Operators).

Alternative syntax

In templates, foreach has the colon syntax too, closed with endforeach;. This is how most PHP views render lists:

PHP
<ul>
<?php foreach ($products as $product): ?>
    <li><?= htmlspecialchars($product['name']) ?></li>
<?php endforeach; ?>
</ul>

Always escape values printed into HTML with htmlspecialchars(), as in PHP and HTML Templates.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? $a = [1, 2, 3]; foreach ($a as $v) { $v *= 10; } echo implode(",", $a);

    The loop variable is a copy of each element, so changing it doesn't affect the array.
  2. 2. In what order does foreach ([2 => "b", 0 => "a", 1 => "c"] as $k => $v) visit the elements?

    PHP arrays are ordered maps, and foreach visits elements in the order they were added. Sort the array first if you need another order.
  3. 3. What should you do right after a foreach loop that uses &$value?

    After the loop, $value still references the last element. unset() removes the name without changing the element. Assigning null would overwrite that element!
  4. 4. Which loop header prints each user's name from rows like ['id' => 1, 'name' => 'Ana']?

    Keyed destructuring picks the 'name' field out of each row. The first form would look for key 0, which these rows don't have.
  5. 5. What happens when you run foreach (null as $x) {}?

    foreach only accepts arrays and objects. Other values produce a warning and the loop body doesn't run. Use ?? [] or return empty arrays instead of null.

Summary

  • foreach ($array as $value) visits every element in insertion order; add $key => to get keys too. Empty arrays skip the loop.
  • The loop variable is a copy: change elements by writing through the key, by building a new array, or by reference.
  • With foreach ($array as &$value), always unset($value) right after the loop, or a later loop can overwrite the last element.
  • Destructure rows in the header: foreach ($rows as [$a, $b]) or foreach ($rows as ['key' => $var]).
  • On objects, foreach visits the properties visible from where it runs; Traversable objects such as ArrayIterator and generators define their own iteration.
  • Passing a non-array, non-object (like null) prints a warning; templates use foreach (...): ... endforeach;.

Next: break, continue and Loop Control