How to use foreach loops

phplogo.jpg

In this lesson we look at how to create a foreach loop in PHP.

There are many uses for loops, especially when you deal with returned data from a database query.

In this example we shall consider an array of values and we will loop through those values and output each.

Line 1: this is our opening PHP code block declaration.
Line 2: we create an array of 5 names. The name of the array is '$names'.

Now we create a foreach loop in order to process through each value in the array:

The format of the foreach loop is fairly straightforward. We start with the foreach function like this: foreach().

Within the round brackets we place $names as $name.

This basically means: take each value in the $names array and assign it to the variable $name.

Now we can process each name as we wish. In this case I will simply echo out each name followed by a line break.

The output from the script will be a simple list of the 5 names:

John
James
Mary
Sharon
Catherine