PHP - foreach loops

by
Jeremy Canfield |
Updated: December 12 2022
| PHP articles
A foreach loop can be used to loop over an array of values.
In this example, an array named fruit contains different types of fruit.
$fruit = array("apple", "banana", "orange", "grapes");
var_dump can be used to print the data structure of the array.
var_dump($fruit);
Which will return the following. Notice that integers 0 1 2 3 are used as the key for each value in the array. If you want, you can define the keys.
array(4) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(6) "orange" [3]=> string(6) "grapes" }
Specific elements can be printed, like this.
echo "fruit[0] = " . $fruit[0] . "<br />";
echo "fruit[1] = " . $fruit[1] . "<br />";
echo "fruit[2] = " . $fruit[2] . "<br />";
echo "fruit[3] = " . $fruit[3] . "<br />";
Which will return the following.
fruit[0] = apple
fruit[1] = banana
fruit[2] = orange
fruit[3] = grapes
Or you can loop through the array.
foreach ($fruit as $value) {
echo "$value<br \>";
}
Which will return the following.
apple
banana
orange
grapes
Let's say you have a hash table (also known as an Associated Array in PHP) that contains keys and values. Here is how to loop through the keys and values.
<?php
$hashtable = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ( $hashtable as $key => $value ) {
print "\$key is $key <br/>";
print "\$value is $value <br/>";
}
?>
Which should return the following.
Peter is 35
Ben is 37
Joe is 43
Did you find this article helpful?
If so, consider buying me a coffee over at