earn how to iterate over arrays using the foreach loop in PHP. See real-world examples, syntax breakdown, and use cases for better PHP code.
foreach LoopThe foreach loop is used to iterate over arrays or objects in PHP. Itβs the easiest way to go through each element in an array.
There are two main ways to use foreach:
// Value only
foreach ($array as $value) {
// Code using $value
}
// Key and value
foreach ($array as $key => $value) {
// Code using $key and $value
}
$value holds the current item in the array.$key holds the current key (index or name) of the item.If you want to change the array values directly, use & to reference the value:
foreach ($array as &$value) {
$value = $value * 2;
}
unset($value); // Always unset to avoid unexpected bugs!
for more details about unset, see Why You Should Always Use unset($value); After a foreach Loop in PHP
β
foreach only works with arrays and objects.unset($value) after using a reference to prevent accidental changes later.foreach Loop<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "Color: $color <br>";
}
?>
Output:
Color: red
Color: green
Color: blue
<?php
$prices = array("apple" => 50, "banana" => 20);
foreach ($prices as $item => $cost) {
echo "$item costs $cost rupees<br>";
}
?>
Output:
apple costs 50 rupees
banana costs 20 rupees
<!DOCTYPE html>
<html>
<head><title>Colors</title></head>
<body>
<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "<h2 style='background-color:$color;'>$color</h2>";
}
?>
</body>
</html>
<?php
$matrix = [
[1, 2],
[3, 4]
];
foreach ($matrix as $row) {
foreach ($row as $item) {
echo "$item ";
}
echo "<br>";
}
?>
Output:
1 2
3 4
<?php
foreach (array("a", "b", "c") as $letter) {
echo $letter . "<br>";
}
?>
foreach when working with arrays β itβs simpler and safer than a for loop.foreach ($arr as $value).unset() afterward).Would you like an infographic or diagram explaining how foreach works step-by-step?
Further reading: