How to Use foreach Loop in PHP: Syntax and Examples
In PHP, use the
foreach loop to iterate over each element in an array easily. The syntax is foreach ($array as $value) to access values or foreach ($array as $key => $value) to access keys and values.Syntax
The foreach loop in PHP is used to loop through arrays. You can use it in two ways:
- Value only:
foreach ($array as $value)loops through each value. - Key and value:
foreach ($array as $key => $value)loops through keys and values.
This makes it easy to access each element without managing counters.
php
<?php // Loop through values only foreach ($array as $value) { // code using $value } // Loop through keys and values foreach ($array as $key => $value) { // code using $key and $value } ?>
Example
This example shows how to use foreach to print each fruit name and its color from an associative array.
php
<?php
$fruits = [
"apple" => "red",
"banana" => "yellow",
"grape" => "purple"
];
foreach ($fruits as $fruit => $color) {
echo "The color of $fruit is $color.\n";
}
?>Output
The color of apple is red.
The color of banana is yellow.
The color of grape is purple.
Common Pitfalls
Common mistakes when using foreach include:
- Trying to modify the array elements without using references.
- Using
foreachon non-arrays or null values. - Confusing the order of
$keyand$value.
Always ensure the variable is an array and use &$value if you want to change elements inside the loop.
php
<?php // Wrong: Trying to change values without reference $numbers = [1, 2, 3]; foreach ($numbers as $num) { $num = $num * 2; // This does not change original array } print_r($numbers); // Outputs original array // Right: Use reference to modify array foreach ($numbers as &$num) { $num = $num * 2; } print_r($numbers); // Outputs modified array // It's a good practice to unset reference after use unset($num); ?>
Output
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Array
(
[0] => 2
[1] => 4
[2] => 6
)
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Value only | Loops through values of array | foreach ($arr as $val) { /* use $val */ } |
| Key and value | Loops through keys and values | foreach ($arr as $key => $val) { /* use $key and $val */ } |
| Modify values | Use reference to change array elements | foreach ($arr as &$val) { $val *= 2; } |
| Non-array error | Avoid using foreach on non-arrays | if (is_array($arr)) { foreach ($arr as $val) {} } |
Key Takeaways
Use foreach to easily loop over arrays without manual counters.
Use foreach ($array as $key => $value) to access both keys and values.
Use references (&$value) in foreach to modify original array elements.
Always check the variable is an array before using foreach to avoid errors.
Foreach loops are simple and readable for array iteration in PHP.