Using the PHP For Loop

The PHP for loop is used to repeat one or more instructions when you know how many times you want those instructions to be repeated. So if you wanted PHP to count to 10, you would use a PHP for loop to make it happen.

If you don't know how beforehand how many times you want to repeat a set of instructions, it is better to use a PHP while loop.

Once you have decided that the for loop is right for you, have a look at the PHP for loop tutorial below.

PHP For Loop Syntax

The syntax for the For Loop in PHP is shown below. Newcomers to PHP should look at it extra closely.

for ($counter = value; condition; change $counter value)
{
    // code to be executed
}

There are three parts needed to make the for loop work, and note that they are separated from each other with semi-colons. First, a counter variable needs to be initialised to some value. Second, we put the check that we will do on the counter variable to see if we should terminate the loop. Last, we tell PHP how to change the value of the counter on each iteration of the loop.

PHP For Loop Example

Have a look at the example below, which demonstrates the behaviour of the for loop:

<?php
 
for ($i = 0; $i < 10; $i++)
{
    echo $i;
    echo '<br />';
}
 
?>

The resulting output will be:

0
1
2
3
4
5
6
7
8
9

We name our counter variable $i and set it to 0. We tell the loop to run only if our counter variable is less than 10. Finally we tell PHP to increment our counter by 1 at the end of each time we run the block of code.

Note that the final output from the loop is 9 and not 10! This is because we set the condition that the loop runs under to be when $i is less than 10. Therefore, the highest value we expect to output is 9.

For loops are useful when handling arrays as we see in our PHP array tutorial. In fact, there is a variation of the PHP for loop known as the PHP for each loop which is especially suited to processing arrays.

We hope this tutorial was useful.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...