PHP Reference ยท Language Constructs and Statements
PHP foreach loop
Reference for the PHP foreach loop: iterate arrays and objects by value, key and reference, destructuring, generators, and the reference-after-loop trap.
foreach walks over every element of an array, or over an object that is iterable (an Iterator, an IteratorAggregate, a generator, or any object's visible properties). It is the safest and most readable way to loop over a collection because you never manage an index yourself.
You can receive just the value, or the key and the value. With & you receive a reference and can change the array's elements in place.
foreach ($prices as $item => $price) { echo "$item costs $price\n"; }
Try it
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.
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.
Syntax
foreach ($iterable as $value) { ... } foreach ($iterable as $key => $value) { ... } foreach ($array as &$value) { ... } foreach ($iterable as [$a, $b]) { ... } foreach ($iterable as $value): // ... endforeach;
| Name | Description |
|---|---|
$iterable |
An array or a Traversable object (or any object, to loop over its accessible properties). |
$key |
Optional variable that receives each key. |
$value |
Variable that receives each value; with & it is a reference to the element. |
Return value: none; foreach is a statement.
Errors: looping over a non-iterable such as null or an int emits a warning ("foreach() argument must be of type array|object") and skips the loop.
Usage notes
- By value is a copy. Without
&, changes to$valuedo not affect the array, and changes to the array inside the loop do not affect the iteration (PHP iterates over a snapshot). - Always
unset($value)after a by-reference loop. The variable remains a reference to the last element; a laterforeachthat reuses the name overwrites that element (the second example shows the duplicate). - Order. Arrays are iterated in insertion order, not key order. Sort first if you need another order.
- Generators and iterators stream one element at a time, so
foreachworks on huge or infinite sequences when youbreakout. - Destructuring in the header unpacks nested arrays; see list and destructuring.
- Modifying the array being iterated. Adding or removing elements by value is safe for the current loop but confusing. Build a new array instead (or use
array_map()). - Objects: only properties visible from the calling scope are visited.
- Using
list()with keys needs PHP 7.1+; array unpacking with string keys inforeachworks in 8.x. - Use
breakandcontinueto stop early or skip an element.