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.

<?php
   $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:

<?php
   $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.

<?php
   $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:

John
James
Mary
Sharon
Catherine

Want to Learn More?

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

Comments

Your email address will not be published.

PHP for Beginners

Enrol in the full course here

PHP, MySQL and PDO

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