Looping Arrays
Iterate over every element of an array with foreach.
Syntax
foreach ($array as $key => $value) { ... }The foreach loop is the easiest way to walk through every element of an array. It works with both indexed and associative arrays.
For indexed arrays you can capture just the value; for associative arrays you can capture the key and the value.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Iterate over an array of order items with foreach to compute a running subtotal.
- Loop through a list of file paths to check each one exists before processing.
- Use foreach with a reference to multiply every price in an array by a VAT factor in place.
More examples
Basic foreach over indexed array
foreach pulls each value from the array in turn without needing a manual index counter.
<?php
$items = ['apple', 'banana', 'cherry'];
foreach ($items as $item) {
echo strtoupper($item) . "\n";
}foreach over associative array
The key => value syntax gives access to both the key and the value on each iteration.
<?php
$totals = ['food' => 120, 'transport' => 45, 'utilities' => 80];
$sum = 0;
foreach ($totals as $category => $amount) {
echo "$category: $$amount\n";
$sum += $amount;
}
echo "Total: $$sum";Modifying values by reference
Adding & before the loop variable modifies the original array; unset() after the loop prevents accidental aliasing.
<?php
$prices = [10.00, 20.00, 30.00];
foreach ($prices as &$price) {
$price = $price * 1.1; // apply 10% VAT
}
unset($price); // always unset the reference
print_r($prices); // [11.0, 22.0, 33.0]
Discussion