Using Loops in PHP

In this short lesson we look at how to construct some simple loops and why they are used.

There are various coding challenges on this website that require you to use loops.

As your coding skills progress and you delve into such things as database connectivity and using database records then the need to loop through results is essential.

The are various looping methods and we will touch on a couple in this lesson.


The for loop is structured as follows:


   //do something here

The loop starts by declaring the initial value of the counter. In this case we start at zero.

The second part is to declare the condition. In this example we test if $i is less than or equal to 10.

The third part is to increment (or decrement) the value of the counter. In this case we are increasing the value of $i by 1 each time through the loop.


$i = 0; 

while($i <= 10) {
    //do something here

This loop produces the same result as the for loop but requires splitting the initial value, conditional test, and incrementor across multiple lines.

Line 2: we set the initial value of the counter

Line 4: the test. We check is $i is less than or equal to 10

Line 6: increment the value of $i by 1


This loop is not used all that often. In fact, I can't recall the last time I ever used one.

$i = 0; 

do {
    //do something here
} while ($i <= 10);


You will probably find yourself using FOR EACH loops with arrays and hence database results.

Let's assume we have an array of names and wish to print out each name.

$names = ['John', 'Mary', 'Sharon']; 

foreach ($names as $name) {
    echo $name .  "<br>";


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

