PHP Foreach Loop
A total different kind of loop is the foreach loop. This loop is used to separately handle each sub-variable out of an array. Each sub-variable may be split into its name and its value.
foreach($array AS $key => $value) {
... execute code ...
}
Each sub-variable of the array $array will be split into its key (stored into $key) and its value (stored into $value) and may be used in the code that’s to be executed ( between the accolades ). It’s a very efficient way to loop through all sub-variables of an array. Each sub-variable will have its key and value stored into separate variables and will go through the code between accolades. Example:
$products = new array(
0 => “product example”,
1 => “another product”
);
foreach($products as $id => $name) {
echo “Product Id: “.$id.” <br />”;
echo “Product Name: “.$name.” <p>”;
}
The output of this script will be:
Product Id: 0
Product Name: product example
Product Id: 1
Product Name: another product
Do realize that the variables inside the foreach loop ( between brackets ) may be given any names. It’s also possible to only use the values of the sub-variables if you don’t need the keys:
$products = new array(
0 => “product example”,
1 => “another product”
);
foreach($products as $name) {
echo “Product Name: “.$name.” <br />”;
}
The output of this script will be:
Product Name: product example
Product Name: another product