Programming in PHP

4.28 (118)

Loops

Another very important idea in programming is the concept of looping or iteration. This is the repetition of specific pieces of code for a specified number of times. This can be incredibly useful if we want to write a list of data from a database to the screen, or if we need to iterate through a large bunch of data and do something with it.

There are three main types of loops in PHP and they are common to other programming languages. They are the for-loop, while-loop and do-while loop (often called repeat until loop). There is another type of loop, however, it will be explained later once we have covered the topic of arrays.

While Loop


The while-loop is very commonly used when you don't know how many times you need to loop over the code. This means, that the loop will keep going, until a condition is met. These are the same types of conditions found in if/else statements. The general structure of a while-loop is as follows:

while (condition) {
    statements;
    statements;
}


As you can see, this is very similar to the conditionals we have previously looked at. First we use the while keyword to tell PHP that we are starting a loop. The condition statement is then placed in brackets, followed by an open curly brace. The statements, or the code you wish to be executed, follow and then the loop is finished with a closing curly brace. So, 'while' the 'condition' is true, the 'statements' are executed, otherwise, the loop will end:

While Loop Example
<?php
$age 
23;
$guess 0;
/* This prints the text to the screen 22 times */
while ($guess != $age) {
    echo 
'You are not ' $guess ' years old!';    
    
$guess++;
}
?>


Here in this example, we have a while loop which writes text to the screen. At first the condition evaluates to true and so the statements are executed. The variable $guess is incremented by 1 each time this loop runs. After 22 loops, the condition is going to evaluate to false as $guess = 23, hence they are the same. After this, the script will finish, or if there were more code, it would execute the following code.

Do-While Loops


As mentioned before, these are often called repeat-until loops. This means, that you are going to repeat a section of code, until the condition evaluates to false. There is a very subtle difference between do-while and standard while loops, in that, a do-while loop will always execute at least once. A standard while loop does have the possibility of never executing.

do {
    statements;
    statements;
} while (condition);


As you can see, the code will execute linearly, so the loop will be entered, and the statements will be executed. Then after the statements have finished executing, the condition will be checked for the NEXT loop. Therefore, this shows that the loops will always execute once. The syntax states that we use the do keyword, followed by an open curly brace and the statements. Then we use the closing curly brace to surround the statements, and follow it by the while keyword. The condition is then written inside brackets, and of course, ends with a semicolon.

Do-While Loop
<?php
$age 
23;

do {
    echo 
'You are ' $age ' years old!';
} while (
$age != 23);
?>

In the code above, I have demonstrated that the statements will only be executed once, as the condition evaluates as false on the first go. Naturally we could use an expression that would first evaluate to true and then switch to false just like the while loops. Note that, if the condition always evaluates to true, you program will run indefinitely. In PHP this is usually not a good idea, however, is very useful in some formal programming languages.

For Loop


Sometimes you know exactly how many times you want a loop to run, and in these cases, it is typical to use a for-loop. In this loop, the amount of times the loop is to run is specified. It is a little bit more complicated than while-loops though extremely useful:

for (start value; condition; increment value) {
    statements;
    statements;
}


This may loop confusing but it isn't once you get the hang of it. For starters, we use the for keyword followed by the configuration of the loop. Then again, the statements are contained within curly braces. The configuration of the loop determines how many times it is going to run.

The start value is a variable declaration with a value assigned, usually zero. The condition is the same as other loops, however, we base the condition on the value of your start variable. Finally the increment value is how the start variable is manipulated each time the loop is run. It is easier to understand if we have an example:

For Loop
<?php
$animal 
'dogs';

for (
$i 0$i <= 10$i++) {
    echo 
'I have ' $i ' ' $animal;
}
?>


Ok! I can imagine that you're thinking this looks crazy, but don't worry. As you can see, the general structure of the for-loop is defined, and you can also see that the statements are surrounded by the curly braces. This means that the loop will loop over the echo statement several times.

In the loop configuration, we see that the start value / variable is defined as $i = 0;. This is just a standard integer and is used in the rest of the configuration. The expression $i <= 10; is the condition of the for-loop. It means that the loop will be executed until $i is no longer less than or equal to 10. The last expression, $i++ indicates to us that the for-loop will automatically increase $i by one every time it finishes one loop over the code. So in this example, the loop will execute a total of eleven times, writing the text to screen eleven times, with the dynamic value of $i included.

Break and Continue


There are two more little things that are useful when using loops and these are the break and continue keywords. Simply put, break will break out of the loop, basically stopping all further looping, and will start executing any code after the loop. The continue keyword will continue the execution of the next loop. So it will stop the execution of the current statements, and will start the next execution of the statements.

Break and Continue
<?php
$age 
23;

for (
$i 0$i 5$i++) {
    if (
$i == 2) {
        break;
    }
    echo 
$i;
}

while (
$age 0) {
    
/* Modulus – Remainder : Check if it is even or odd */
    
$x $age 2
    $age
--;
    if (
$x == 1) {
        continue;
    }
    echo (
$age 1);
}
?>


Those are two simple examples of the break and continue keywords. In the first loop, without the break keyword, the loop would execute five times and write the numbers 1 to 5 to the screen. However, with the break inside the if statement, we see that once $i = 2 then the loop will end. Therefore, only the numbers 0 and 1 will be written to screen.

In the second example of the continue keyword, we see that initially we would write the $age-- to the webpage 22 times, however, we calculate if the age is odd or even using the modulus function (getting the remainder), and if it is odd, then we continue. Therefore, on every odd-numbered age the loop stops and starts again from the beginning, so in this example, only the even-numbered ages would be printed to the page (22, 20… 2).

Loops are commonly used to manipulate large groups of data of the same type. The loop will iterate over all the data and perform the exact same process on all the data. Loops can also be used for many other processes such as complicated calculations as well as trivial things such as writing out how many dogs you have!
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 6 of 10    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter