FreeKB - PHP foreach loops
PHP - foreach loops

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.



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.



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 4a898 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |