11 Sep 09 PHP Programming Tutorial: For Loops



PHP For Loops are similar to While Loops in the sense that you set a condition and the loop continues if the condition is met.

The basic structure of a For Loop is:

<?php
    for (Start;Test;End)
    {
        php statements;
    }
?>

Let’s examine the first line of the For Loop.

Start: this statement executes at the beginning of the loop. You may set a value here (see example below) or any other condition that will execute before the loop starts.

Test: these conditions are tested every time in a loop. As long as this condition is true, the loop will loop again.

End: this statement executes at the end of the loop.

Many programmers use For Loops to execute a script a set number of times. Here’s an example:

<?php
    for ($x = 1; $x <= 5; $x++)
    {
        echo "Hello, I am loop iteration number $x.<br />"
    }
?>

What we have is a basic counter, just like we used in the PHP While Loops Tutorial. Every time the loop is used, the counter goes up one.

In the Start section of the For Loop, we gave the variable $x a value of 1. In the Test section, we told PHP to continue with the script as long as the $x variable is less than or equal to 5. In the End section, we’re adding one to the $x variable. Notice that each section is separated by a semicolon (;).

And this is the result of the code above:

Hello, I am loop iteration number 1.
Hello, I am loop iteration number 2.
Hello, I am loop iteration number 3.
Hello, I am loop iteration number 4.
Hello, I am loop iteration number 5.

As always, feel free to experiment on your local WAMP installation and try changing the numbers to see the results.

Let’s move onto For Each Loops. Or go back to Building PHP Scripts.

Leave a Comment