PHP For Loop

PHP For Loops

So what’s a loop then? A loop is something that goes round and round. If I told you to move a finger around in a loop, you’d have no problem with the order (unless you have no fingers!) In programming, it’s exactly the same. Except a programming loop will go round and round until you tell it to stop. You also need to tell the programme two other things - where to start your loop, and what to do after it’s finished one lap (known as the update expression).

You can programme without using loops. But it’s an awful lot easier with them. Consider this.

You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4. You could do it like this:

$answer = 1 + 2 + 3 + 4;
print $answer;

Fairly simple, you think. And not much code, either. But what if you wanted to add up a thousand numbers? Are you really going to type them all out like that? It’s an awful lot of typing. A loop would make life a lot simpler. You use them when you want to execute the same code over and over again.

We'll discuss a few flavours of programming loops, but as the For Loop is the most used type of loop, we'll discuss those first.


For Loops

Here’s a PHP For Loop in a little script. Type it into new PHP script and save your work. Run your code and test it out.

<?PHP
$counter = 0;
$start = 1;
for($start; $start < 11; $start++) {
$counter = $counter + 1;
print $counter . "<BR>";
}
?>

How did you get on? You should have seen the numbers 1 to 10 printed on your browser page.

The format for a For Loop is this:

for (start valueend valueupdate expression) {
}

The first thing you need to do is type the name of the loop you’re using, in this case for. In between round brackets, you then type your three conditions:

Start Value

The first condition is where you tell PHP the initial value of your loop. In other words, start the loop at what number? We used this:

$start = 1;

We’re assigning a value of 1 to a variable called $start. Like all variables, you can make up your own name. A popular name for the initial variable is the letter i . You can set the initial condition before the loop begins, like we did:

$start = 1;
for($start; $start < 11; $start++) {

Or you can assign your loop value right in the For Loop code:

for($start = 1; start < 11; start++) {

The result is the same – the start number for this loop is 1

End Value

Next, you have to tell PHP when to end your loop. This can be a number, a Boolean value, a string, etc. Here, we’re telling PHP to keep going round the loop while the value of the variable $start is Less Than 11.

for($start; $start < 11; $start++) {

When the value of $start is 11 or higher, PHP will bail out of the loop.

Update Expression

Loops need a way of getting the next number in a series. If the loop couldn’t update the starting value, it would be stuck on the starting value. If we didn’t update our start value, our loop would get stuck on 1. In other words, you need to tell the loop how it is to go round and round. We used this:

$start++

In a lot of programming language (and PHP) the double plus symbol (++) means increment (increase the value by one). It’s just a short way of saying this:

$start = $start + 1

You can go down by one (decrement) by using the double minus symbol (--), but we won’t go into that.

So our whole loop reads “Starting at a value of 1, keep going round and round while the start value is less than 11. Increase the starting value by one each time round the loop.”
Every time the loop goes round, the code between our two curly brackets { } gets executed:

$counter = $counter + 1;
print $counter . "<BR>";

Notice that we’re just incrementing the counter variable by 1 each time round the loop, exactly the same as what we’re doing with the start variable. So we could have put this instead:
$counter ++

The effect would be the same. As an experiment, try setting the value of $counter to 11 outside the loop (it’s currently $counter = 0). Then inside the loop, use $counter- - (the double minus sign). Can you guess what will happen? Will it crash, or not? Or will it print something out? Better save your work, just in case!

(PHP 4, PHP 5)
for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:
for (expr1; expr2; expr3)
    statement
The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.
In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.
Consider the following examples. All of them display the numbers 1 through 10:
<?php/* example 1 */
for ($i 1$i <= 10$i++) {
    echo 
$i;
}
/* example 2 */
for ($i 1; ; $i++) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
}
/* example 3 */
$i 1;
for (; ; ) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
    
$i++;
}
/* example 4 */
for ($i 1$j 0$i <= 10$j += $i, print $i$i++);?>
Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.
PHP also supports the alternate "colon syntax" for for loops.
for (expr1; expr2; expr3):
    statement
    ...
endfor;
It's a common thing to many users to iterate through arrays like in the example below.
<?php/*
 * This is an array with some data we want to modify
 * when running through the for loop.
 */
$people = array(
    array(
'name' => 'Kalle''salt' => 856412),
    array(
'name' => 'Pierre''salt' => 215863)
);

for(
$i 0$i count($people); ++$i) {
    
$people[$i]['salt'] = mt_rand(000000999999);
}
?>
The above code can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly callingcount():
<?php
$people 
= array(
    array(
'name' => 'Kalle''salt' => 856412),
    array(
'name' => 'Pierre''salt' => 215863)
);

for(
$i 0$size count($people); $i $size; ++$i) {
    
$people[$i]['salt'] = mt_rand(000000999999);
}
?>