PHP Foreach Loop Example

Iterate over arrays and their keys with foreach. Edit the code below and press Run to execute it with real PHP in your browser.

Code Editor
Output
Apple
Banana
Cherry
name: John
age: 30
city: New York

How this foreach loop example works

foreach is the standard way to loop over arrays. foreach ($array as $value) gives each value; foreach ($array as $key => $value) also gives the key, which is essential for associative arrays.

Modify elements by reference

Prefix the value with & to change the original array. Always unset() the reference afterwards to avoid surprising bugs in later loops.

<?php
$prices = [10, 20, 30];
foreach ($prices as &$price) {
    $price *= 2;
}
unset($price);
echo implode(", ", $prices);

Output:

20, 40, 60