foreach Loop
The best way to loop over the elements of an array.
Syntax
foreach ($array as $value) { ... }The foreach loop works only on arrays and objects. It gives you each element in turn without needing a counter.
Use the $key => $value form when you also need the key.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Render each item in a shopping cart array as an HTML table row without a manual index.
- Validate each field in a submitted form data array using a foreach and collect errors.
- Extract all values for a specific key from an array of database rows with foreach.
More examples
foreach over simple array
foreach pulls each value from a list in sequence without needing a counter variable.
<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
echo ucfirst($fruit) . "\n";
}foreach with key and value
Unpacking key => value in foreach exposes both the product name and its data on every iteration.
<?php
$cart = [
'Widget' => ['qty' => 2, 'price' => 9.99],
'Gadget' => ['qty' => 1, 'price' => 24.99],
];
$total = 0;
foreach ($cart as $name => $item) {
$line = $item['qty'] * $item['price'];
$total += $line;
echo "$name: $$line\n";
}
echo "Total: $$total";Extracting a column with foreach
Appending a single field inside foreach extracts a column from a 2-D result set into a flat array.
<?php
$users = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 3, 'name' => 'Carol'],
];
$ids = [];
foreach ($users as $user) {
$ids[] = $user['id'];
}
echo implode(', ', $ids); // 1, 2, 3
Discussion