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";
}
?>Modifying an array with a reference
<?php
$prices = [10, 20, 30];
foreach ($prices as &$price) {
$price = $price * 2;
}
unset($price);
print_r($prices);
?>- 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.