O'Reilly logo

Learning PHP and MySQL by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Looping

Now change the flow of your PHP program based on comparisons, but if you want to repeat a task until a comparison is FALSE, you will need to use looping. Each time the code in the loop executes, it is called an iteration. It's useful for many common tasks such as displaying the results of a query by looping through the returned rows. PHP provides the while, for, and while . . . do constructs to perform loops.

Each of the loop constructs requires two basic pieces of information. First, when to stop looping is defined just like the comparison in an if statement. Second, the code to perform is also required and specified either on a single line or within curly braces. A logical error would be to omit the code in the loop, causing an infinite loop.

The code is executed as long as the expression evaluates to TRUE. To avoid an infinite loop, which would loop forever, your code should affect the expressions so that it becomes FALSE. When this happens, the loop stops, and execution continues with the next line of code, following the logical loop.

while Loops

The while loop takes the expression followed by the code to execute. Figure 4-3 illustrates how a while loop processes.

How a while loop executes

Figure 4-3. How a while loop executes

The syntax is for a while loop is:

while (expression)
{
  code to
 execute;
}

An example is shown in Example 4-14.

Example 4-14. A sample while loop that counts to 10

<?php
$num = 1;

while ($num <= 10){
    print "Number is $num<br />\n";
    $num++;
}

print 'Done.';
?>

Example 4-14 produces:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Done.

Before the loop begins, the variable $num is set to 1. This is called initializing a counter variable. Each time the code block executes, it increases the value in $num by 1 with the statement $num++;. After 10 iterations, the evaluation $num <= 10 becomes FALSE and the loop stops, which then prints Done..

Warning

Be careful not to create an infinite loop. It has the undesirable effects of not returning your page and taking a lot of processing time on the web server.

do . . . while Loops

The do . . . while loop takes an expression such as a while statement but places it at the end. The syntax is:

do {
  code to execute;
} (expression);

This loop is useful when you want to execute the block of code once regardless of the value in the expression. For example, let's count to 10 with this loop, as in Example 4-15.

Example 4-15. Counting to 10 with do...while

<?php

$num = 1;

do {
    echo "Number  is ".$num."<br />";
    $num++;
} while ($num <= 10);

echo "Done.";

?>

Example 4-15 produces the same results as Example 4-14; if you change the value of $num to 11, the loop processes differently.

<?php

$num = 11;

do {
    echo $num;
    $num++;
} while ($num <= 10);

?>

This produces:

11

The code in the loop displays 11 because the loop always executes at least once. Following the pass, while evaluates to FALSE, causing execution to drop out of the do . . . while loop.

for Loops

for loops provide the same general functionality as while loops, but also provide for a predefined location for initializing and changing a counter value. Their syntax is:

for (initialization expression; test expression; modification expression){
  code that is executed;
}

Figure 4-4 shows a flowchart for a for loop.

How a for loop executes

Figure 4-4. How a for loop executes

An example for loop is:

<?php
for ($num = 1; $num <= 10; $num++) {
    print "Number is $num<br />\n";
}
?>

This produces:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10

When your PHP program process the for loop, the initialization portion is evaluated. For each iteration of the portion that increments, the counter executes, followed by a check to see whether you're done. The result is a much more compact and easy-to-read statement.

Tip

When specifying your for loop, if you don't want to include one of the expressions, such as the initialization expression, you may omit it, but you must still include the separating semicolons (;). Example 4-16 shows the usage of a for loop without the initialization expression.

Breaking Out of a Loop

PHP provides the equivalent of an emergency stop button for a loop: the break statement. Normally, the only way out of a loop is to satisfy the expression that determines when to stop the loop. If the code in the loop finds an error that makes continuing the loop pointless or impossible, you can break out of the loop by using the break statement. It's like getting your shoelace stuck in an escalator. It really doesn't make any sense for the escalator to keep going!

Possible problems you might encounter in a loop include running out of space when writing to a file or attempting to divide by zero. In Example 4-16, we simulate what can happen if you divide based on an unknown entry initialized from a form submission (that could be a user-supplied value). If your user is malicious or just plain careless, she might enter a negative value where you are expecting a positive value (although this should be caught in your form validation process). In the code that is executed as part of the loop, the code checks to make sure $counter is not equal to zero. If it is, the code calls break.

Example 4-16. Using break to avoid division by zero

<?php

$counter = -3;

for (; $counter < 10; $counter++){
    // Check for division by zero
    if ($counter == 0){
        echo "Stopping to avoid division by zero.";
        break;
    }

    echo "100/$counter<br />";
}

?>

This displays:

100/−3
100/−2
100/−1
Stopping to avoid division by zero.

Of course, there may be times when you don't want to just skip one execution of the loop code. The continue statement performs this for you.

continue Statements

You can use the continue statement to stop processing the current block of code in a loop and jump to the next iteration of the loop. It's different from break; in that it doesn't stop processing the loop entirely. You're basically skipping ahead to the next iteration. Make sure you are modifying your test variable before the continue statement, or an infinite loop is possible.

Example 4-17 shows the preceding example using continue instead of break.

Example 4-17. Using continue instead of break

<?php

$counter =− 3;

for (; $counter < 10; $counter++){
    // Check for division by zero
    if ($counter == 0){
        echo "Skipping to avoid division by zero.<br />";
        continue;
    }

    echo "100/$counter<br />";
}

?>

Example 4-17 displays:

100/−3
100/−2
100/−1
Skipping to avoid division by zero.
100/1
100/2
100/3
100/4
100/5
100/6
100/7
100/8
100/9

Notice that the loop skipped over the $counter value of zero but continued with the next value.

We've now covered all of the major program flow language constructs. We've discussed the building blocks for controlling program flow in your programs. Expressions can be as simple as TRUE or FALSE and as complex as relational comparison with logical operators. The expressions combined with program flow control constructs like the if statement and switch make decision making easy.

We also discussed while, while . . . do, and for loops. Loops are very useful for common dynamic web page tasks such as displaying the results from a query in an HTML table.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required