The foreach loop is designed specifically for iterating over arrays and objects — the loop you will use most often in PHP.
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
$person = ["name" => "Alice", "age" => 30, "city" => "Paris"];
foreach ($person as $key => $value) {
echo "$key: $value <br>";
}
$users = [
["name" => "Alice", "role" => "admin"],
["name" => "Bob", "role" => "editor"],
];
foreach ($users as $user) {
echo "{$user["name"]} is an {$user["role"]}<br>";
}
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as &$num) {
$num *= 2;
}
unset($num); // always unset reference after loop
print_r($numbers); // [2, 4, 6, 8, 10]