Using Loops in PHP

phplogo.jpg

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:

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

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.

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.