PHP foreach Keyword
Example
Print all of the values in an array:
<?php
$cars = ["Ford", "Volvo", "BMW"];
foreach($cars as $car) {
echo
"$car <br>";
}
?>
Try it Yourself »
Definition and Usage
The foreach
keyword is used to create
foreach loops, which loops through a block of code for each element in an array.
Related Pages
Read more about foreach loops in our PHP foreach Loop Tutorial.
More Examples
Example
Print keys and values from an associative array:
<?php
$people = [
"Peter" => "35",
"Ben" => "37",
"Joe" => "43"
];
foreach($people as $person => $age) {
echo "$person is $age
years old";
echo "<br>";
}
?>
Try it Yourself »
❮ PHP Keywords
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.