Phone: 415-963-0926 | 415-963-0927
Log in Currency: £ $
Basket: 0 domains, no hosting yet
 

PHP programming tutorial

4. Loops

You can use the knowledge you've gained from conditionals to apply similar principals to loops. PHP has four different loop constructs. They are:

  • While
  • Do ... while
  • For
  • Foreach

We'll start with the simplest, 'while' loops. A 'while' loop will continue running until the specified condition is FALSE. Let's see a very basic example:

<?php
    $c 
1;    
    while (
$c <= 10) {
        echo 
$c "<br />\n";    
        
$c++;
    }
?>

This will output the numbers 1 - 10 inclusive separated by HTML linebreaks and a new line. If the condition is FALSE to start with, the code inside the loop is never executed. The following code will do nothing:

<?php
    $c 
11;
    while (
$c <= 10) {
        echo 
$c "<br />\n";    
        
$c++;
    }
?>

The 'do-while' loop

What if you always want to execute the code at least once? A 'do ... while' loop is essentially the same as a while loop, except that the code is always run at least once and the condition is checked after it's run. Here's an example:

<?php
    $c
=1;
    do {
        echo 
$c "<br />\n";
        
$c++;
    } while (
$c <= 10);
?>

The 'for' loop

A for loop consists of three statements - the first is usually used as an initialiser and runs before the loop starts, the second is a conditional expression that must evaluate to TRUE or FALSE, when it is FALSE, the loop stops, and the third is normally used as an incrementer and is run after each run through the code. Let's see a simple example:

<?php
    
for ($c 1$c <= 10$c++) { 
        echo 
$c "<br />\n";
    }
?>

We've now combined three of the operations necessary for the same loop into one line of code so it's a much shorter and easier-to-read. In a lot of cases you can condense your loop into quite a small amount of code with a 'for' loop so they're used a lot for that reason.

The 'foreach' loop

The 'foreach' loop is a special kind of loop in that it's designed specifically to iterate over arrays. You use this to apply the same piece of code to every element in an array. Here's a very simple example:

<?php
    $arr 
= array('foo''bar''thud''grunt');
    foreach (
$arr as $value) {
        echo 
$value "<br />\n";
    }
?>

This will output the words 'foo', 'bar', 'thud' and 'grunt' each separated by an HTML linebreak and a new line.

You can also use a 'foreach' loop to get both the key and the value from the array - this is normally more useful. The syntax for this uses the double-arrow like this:

<?php
    $arr 
= array('foo''bar''thud''grund');
    foreach (
$arr as $key => $value) {
        echo 
$key ": " $value "<br />\n";
    }
?>

This code will produce the following output:

0: foo<br />
1: bar<br />
2: thud<br />
3: grund<br />

This is normally more useful in the case of string keys (associative arrays), as in this example:

<?php
    $arr 
= array('firstname' => 'Alice''surname' => 'Smith''title' => 'Mrs.');
    foreach (
$arr as $key => $value) {
        echo 
$key ": " $value "<br />\n";
    }
?>

This would produce the following:

firstname: Alice<br />
surname: Smith<br />
title: Mrs.<br />

The 'break' statement

The 'break' statement can be used from inside any kind of loop and it instructs the loop's execution to stop immediately and for program flow to continue on to the next statement after the loop. This can be used when a specific condition has been met that means the loop no longer needs to continue. Let's see a very simple example:

<?php
    
for ($i 0$i <= 10$i++) {
        if (
$i == 5) {
            break;
        }
        echo 
$i "<br />\n";
    }
?>

This code will output the numbers 0 to 4, but stop before printing the number 5 because when the counter gets to that point, the loop is broken out of - otherwise it would continue on to 10.

The 'continue' statement

The continue statement allows you to skip out the rest of the code in the loop but without breaking out of the loop entirely. The loop simply continues on to its next iteration. Here's an example:

<?php
    
for ($i 0$i <= 10$i++) { 
        echo 
$i;
        if (
$i <= 5) {
            echo 
"<br />\n";
            continue;
        }
        echo 
" is more than 5<br />\n";
    }
?>

This will produce the following output:

0<br />
1<br />
2<br />
3<br />
4<br />
5<br />
6 is more than 5<br />
7 is more than 5<br />
8 is more than 5<br />
9 is more than 5<br />
10 is more than 5<br />

Here you can see that for the first five iterations of the loop, the number is less than or equal to 5, so the loop prints the number but continues without running the last line which adds the words 'is more than 5'.

Previous chapter... (3. Conditionals)
Next chapter... (5. Functions)
 

Back to top


About Digital Crocus:

Digital Crocus offer affordable UK web hosting to get you up and running from just $32.49 per year or $3.99 per month. Our most basic account would be enough to get started learning PHP and host a few websites with a moderate amount of traffic. We offer easy upgrade options as your requirement grows and a friendly and helpful email and phone customer support service. If you're looking to buy web hosting, consider giving us a try - under our money back guarantee we'll refund you if you're not 100% satisfied.

About the author:

Kieran Simkin is an experienced software developer and co-founder of Digital Crocus. Kieran is also a keen amateur photographer and musician and has a personal portfolio which you can see online.

Questions Resellers Hosting Domains Home