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.

   $names = array('John', 'James', 'Mary', 'Sharon', 'Catherine');

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:

   $names = array('John', 'James', 'Mary', 'Sharon', 'Catherine');
   foreach($names as $name){
      // do something here

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.

   $names = array('John', 'James', 'Mary', 'Sharon', 'Catherine');
   foreach($names as $name){
      echo $name . "<br>";

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


Want to Learn More?

Become a member and get access to the member only area of this site here.


Your email address will not be published.

PHP for Beginners

Enrol in the full course here


Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.