TOC

The community is working on translating this tutorial into Persian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Basic PHP:

Loops

As within any other programming language, the ability to repeat a piece of code X number of times is very important. That's what we use loops for, and PHP offers us 4 different looping mechanisms. This chapter will walk through all of them, explaining how they work with an example.

The while loop

The while loop is probably the simplest of them all. It simply repeats the block of code as long as the statement inside it evaluates to true. An example could look like this:

<?php
$i = 0;
while($i < 5)
{
    echo $i."<br>";
    $i++;
}
?>

Try running this piece of code. It will count to 4, since we continue until $i is no longer less than 5. Each time the loop iterates, we add 1 to the counting value, $i, as well as output the current value. Whatever you decide to put between the parentheses of the while loop, it has to be able to evaluate into a Boolean value, that is, true or false.

The do-while loop

This one works almost exactly like the while loop, with one important difference: With the while loop, the statement is checked before the loop is entered - with the do-while loop, it's checked at the end of an iteration. This means that with the do-while loop, you are guaranteed at least one iteration - with a regular while loop, the code within it may never be reached, if the statement is never evaluated to true. Here is an example showing just this behavior:

<?php
$i = 0;
do
{
    echo $i."<br>";
    $i++;
} while($i < 0);
?>

With a regular while loop, nothing would ever be printed to the user, because $i is 0, and therefore not less than 0 at any point. However, since this is a do-while loop, we get an iteration for free. Afterwards, PHP realizes that the statement does not evaluate to true, and exits the loop.

The for loop

One of the most common loops in PHP, which you might recognize from other programming languages, is the for loop. It will look a bit more complicated than the while loop, but with a bit of practice you may get to like it better. Here is an example using the for loop:

<?php
for($i = 0; $i < 5; $i++)
{
    echo $i."<br />";
}
?>

This will produce the exact same output as the previous while loop, but as you can see, we do it with fewer lines of code. The counter variable is both initialized, tested and incremented with the same line: First we declare it and assign a value to it, then we write the statement to evaluate, and then we increase (or decrease, which is of course possible as well) the variable. Each part is separated with a semicolon. The for loop is nice and compact and good for all situations where you wish to keep track of the amount of iterations.

The foreach loop

The foreach loop in PHP is for iterating through an array. Actually, it only works on arrays, and PHP will issue an error if you try to use it on an unitialized variable, or a variable which doesn't contain an array. The foreach loop comes in two different flavors - here is an example of the first one. Oh, and since arrays haven't been introduced yet, think of them as a list of items for now. In a later chapter, we will look into arrays and how to use them.

<?php
$animals = array("Dog", "Cat", "Snake", "Tiger");

foreach($animals as $animal)
    echo $animal . "<br />";
?>

The nice thing about the foreach loop is that it's designed to work only with arrays, which in turn makes the whole process easier. In each iteration, $animal is assigned the value of the current place in the array, giving us easy access to it. This little snippet of code will simply output a list of the items (in this case animals) in the array.

In this version of the foreach loop, we only get access to the value of the loop. However, each item in an array consists of a key and a value. In our example, we let PHP assign the keys automatically by not explicitly setting them. This is explained in details in the chapter about arrays. In case you need to access the key of the current item in the iteration as well, use the secondary foreach construct, like this:

<?php
$animals = array(1 => "Dog", "Cat", "Snake",    "Tiger");

foreach($animals as $key => $value)
    echo "Animal number " . $key . " is a " . $value . "<br />";
?>

As simple as that.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!