PHP foreach Loop
In this page:
What is a foreach Loop?
The foreach loop is PHP's dedicated tool for walking through every element of an array without manually tracking an index. Where a for loop needs you to manage a counter and bounds yourself, foreach hands you each value directly, which is why it's the loop PHP developers reach for first when the goal is simply "do this for every item."
Example: What is a foreach Loop?
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Looping With Keys and Values
Writing foreach ($array as $key => $value) gives you both the array key and its value on each pass, which matters enormously for associative arrays where the key carries real meaning — a username, a product ID, a config option name. Without the => $value form you'd only see the values and lose that context entirely.
Example: Looping With Keys and Values
<?php
$config = ["theme" => "dark", "lang" => "en"];
foreach ($config as $key => $value) {
echo "$key: $value\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Modifying Values by Reference
Adding an ampersand, foreach ($array as &$value), makes $value a reference into the original array rather than a copy, so changes you make inside the loop body actually update the array itself. This is the only built-in way to modify array elements in place during a foreach pass.
Example: Modifying Values by Reference
<?php
$numbers = [1, 2, 3];
foreach ($numbers as &$value) {
$value *= 2;
}
unset($value);
print_r($numbers);
?>
Login to try C/C++/Java/PHP code in the editor
The Dangling Reference Pitfall
After a by-reference foreach finishes, $value still points at the array's last element — reusing that same variable name in a later, non-reference foreach can silently overwrite that last element with unrelated data. The fix is a single unset($value); right after the reference loop ends, and skipping it is one of PHP's most common array bugs.
Example: The Dangling Reference Pitfall
<?php
$numbers = [1, 2, 3];
foreach ($numbers as &$value) {
$value *= 2;
}
unset($value); // without this, the next foreach below would corrupt the last element
foreach ($numbers as $value) {
echo $value . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
foreach With Nested and Multidimensional Arrays
Nesting one foreach inside another is the natural way to walk a multidimensional array, such as a list of associative arrays representing rows of data — the outer loop gives you each row, and an inner loop or direct key access reads that row's individual fields.
Example: foreach With Nested and Multidimensional Arrays
<?php
$rows = [
["name" => "Alice", "age" => 30],
["name" => "Bob", "age" => 25],
];
foreach ($rows as $row) {
echo $row["name"] . " is " . $row["age"] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: