The foreach loop is specifically for looping through Arrays. It is the most common loop used in modern web development because data from databases and APIs is almost always returned in array format.
This is the simplest form of the foreach loop. It loops through every element in the array and assigns the current value to a variable.
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
For Associative Arrays, you often need both the "Key" (the name/label) and the "Value" (the data). You can access both using the $key => $value syntax.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $name => $years) {
echo "$name is $years years old. <br>";
}
?>
for or while, you don't need to specify a condition or increment. The loop will automatically stop when it reaches the last element of the array.
foreach whenever you are working with lists of data, such as a list of users, products in a cart, or navigation menu items.
By default, foreach works on a copy of the array. If you want to change the actual values in the original array, you must add an & before the value variable.
<?php
$nums = [1, 2, 3];
foreach ($nums as &$val) {
$val *= 2; // Doubles the original value
}
print_r($nums); // Outputs: [2, 4, 6]
?>