The foreach loop in PHP is specifically designed to iterate through arrays, making it easy to access array elements without using an index.
Syntax of PHP Foreach Loop
<?php
foreach ($array as $value) {
// Code to execute
}
foreach ($array as $key => $value) {
// Code to execute
}
?>
📝 Example 1: Loop Through an Indexed Array
Prints each value in an array of colors.
<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
echo "Color: $color <br>";
}
?>
📝 Example 2: Loop Through an Associative Array
Prints keys and values from an associative array.
<?php
$person = array("Name" => "Alice", "Age" => 25, "City" => "New York");
foreach ($person as $key => $value) {
echo "$key: $value <br>";
}
?>
📝 Example 3: Modify Array Values Inside Foreach
Use & to update array values.
<?php
$numbers = array(1, 2, 3, 4);
foreach ($numbers as &$num) {
$num *= 2;
}
print_r($numbers);
?>
🎯 When to Use Foreach?
- When working with arrays.
- When you don’t need a manual index counter.
- When modifying array values inside the loop.
📝 Practice Time!
Try modifying the examples to see how foreach works with different types of arrays.