CODING ACADEMY

View Original

How to use foreach loops

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.

See this content in the original post

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:

See this content in the original post

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.

See this content in the original post

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

John
James
Mary
Sharon
Catherine