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.

FOR LOOP

The for loop is structured as follows:

<?php

for($i = 0; $i <= 10; $i++)
{
   //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.

WHILE LOOP

<?php 
$i = 0; 

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

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

DO WHILE LOOP

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

<?php 
$i = 0; 

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

FOR EACH LOOP

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.

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

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.