PHP Loops Tutorial

By Tejal Patwardhan


Introduction

There are a few types of loops in PHP. These include for loops, foreach loops, do...while loops and while loops. Most programs require at least one loop. So lets get looping!

For Loops

When we already know how many times we want to run the loop, we use a for loop.

The syntax is the following.

For advanced learners, we can put multiple expressions in the first and last clauses. Just separate them with commas. Let's take a look.

Let's say we wanted to display the numbers 0-5 using a loop. We could loop through the numbers 0-5 by adding 1 to the variable x each time, and then displaying x.

This loop outputs the following.

Or we could put 'echo $x' next to the code that is executed at the end of each loop.

Foreach Loops

Foreach loops allow us to loop through arrays. Each time, the loop stores the value in the cell as the variable and uses the variable to execute the code. Every iteration moves to the next cell until the array is out of cells.

The syntax is the following.

Let's look at an example. We can loop through an array containing selected lyrics from Michael Jackson's "ABC" and display them.

This loop outputs the following.

While Loops

To execute some code while a condition is true, we use while loops. The syntax here is really simple.

For example, to display 5 troll faces in a row (the loop iterates until the variable x is equal to 5), we can use the following.

This loop outputs the following.

Do...While Loops

To execute a block of code once before beginning a while loop, we use do...while loops. The syntax here is different from what we have already covered.

Let us display a little troll face 5 times (while variable x is less than 5).

This loop outputs the following.

Conclusion

You are now finished with the tutorial! Bonus points if you noticed something special on each of the images of code. Watermark, anyone? #obnoxious