PHP Foreach Loop

The foreach loop is built specifically for arrays, visiting every element in turn without you having to manage a counter or worry about the array's length.

Made for arrays

When your goal is simply to touch every item in an array, foreach is the clearest and safest choice. It handles the bookkeeping for you: there is no counter to initialize, no length to check, and no risk of running past the end. On each pass it hands you the next element automatically, and it works with both indexed arrays and associative arrays.

Looping over values

<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
    echo "I like $fruit\n";
}
?>

The syntax reads almost like plain English: for each element in $fruits, put it in $fruit and run the body. The loop stops on its own once every element has been visited.

Getting the key as well as the value

Arrays in PHP are really pairs of keys and values. With the key => value form of foreach you can grab both at once. This is essential for associative arrays, where the keys carry meaning such as a setting name or a column label.

Looping with key and value

<?php
$ages = [
    "Alice" => 30,
    "Bob" => 25,
    "Carol" => 35,
];
foreach ($ages as $name => $age) {
    echo "$name is $age years old\n";
}
?>
FormGives youUse for
foreach ($arr as $value)Each value onlySimple lists where the key does not matter
foreach ($arr as $key => $value)Both the key and the valueAssociative arrays or when position matters
Note: By default foreach works on a copy of each value, so editing the loop variable does not change the original array. To modify the array in place, put an ampersand before the value variable to make it a reference: foreach ($arr as &$value).

Modifying an array with a reference

<?php
$prices = [10, 20, 30];
foreach ($prices as &$price) {
    $price = $price * 2;
}
unset($price);
print_r($prices);
?>
Note: After a foreach loop that uses a reference (&$value), always call unset() on that variable. If you skip it, the variable still points at the last element, and a later loop or assignment can silently overwrite that element.
  • Prefer foreach over for when you just need to visit every element of an array.
  • Use the key => value form to read associative array keys.
  • Use a reference only when you genuinely need to change the array, and unset the reference afterwards.
  • The break and continue statements work inside foreach exactly as in other loops.