Loops


So far we've looked at decisions that a script can make about what code to execute. Scripts can also decide how many times to execute a block of code. Loop statements are specifically designed to enable you to perform repetitive tasks, as they will continue to operate until a specified condition is achieved, or you explicitly choose to exit the loop.

The while Statement

The while statement looks similar in structure to a basic if statement, but has the ability to loop:

 while (expression) {       // do something } 

Unlike an if statement, a while statement will execute for as long as the expression evaluates to TRue, over and over again if need be. Each execution of a code block within a loop is called an iteration. Within the block, you usually change something that affects the while statement's expression; otherwise, your loop continues indefinitely. For example, you may use a variable to count the number of iterations, and act accordingly. Listing 6.6 creates a while loop that calculates and prints multiples of 2 up to 24.

Listing 6.6. A while Statement
 1: <?php 2: $counter = 1; 3: while ($counter <= 12) { 4:     echo "$counter times 2 is ".($counter * 2)."<br>"; 5:     $counter++; 6: } 7: ?> 

In this example, we initialize the variable $counter in line 2, with a value of 1. The while statement in line 3 tests the $counter variable, so that as long as the value of $counter is less than or equal to 12, the loop will continue to run. Within the while statement's code block, the value of $counter is multiplied by 2 and the result is printed to the browser. In line 5, the value of $counter is incremented. This step is extremely important, for if you did not increment the value of the $counter variable, the while expression would never resolve to false and the loop would never end.

Put these lines into a text file called testwhile.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 1 times 2 is 2 2 times 2 is 4 3 times 2 is 6 4 times 2 is 8 5 times 2 is 10 6 times 2 is 12 7 times 2 is 14 8 times 2 is 16 9 times 2 is 18 10 times 2 is 20 11 times 2 is 22 12 times 2 is 24 

The do...while Statement

A do...while statement looks a little like a while statement turned on its head. The essential difference between the two is that the code block is executed before the truth test and not after it:

 do {     // code to be executed } while (expression); 

By the Way

The test expression of a do...while statement should always end with a semicolon.


This type of statement is useful when you want the code block to be executed at least once, even if the while expression evaluates to false. Listing 6.7 creates a do...while statement. The code block is executed a minimum of one time.

Listing 6.7. The do...while Statement
 1: <?php 2: $num = 1; 3: do { 4:     echo "The number is: $num<br>"; 5:     $num++; 6: } while (($num > 200) && ($num < 400)); 7: ?> 

The do...while statement tests whether the variable $num contains a value that is greater than 200 and less than 400. In line 2, we have initialized $num to 1, so this expression returns false. Nonetheless, the code block is executed at lease one time before the expression is evaluated, so the statement will print a single line to the browser.

Put these lines into a text file called testdowhile.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 The number is: 1 

If you change the value of $num in line 2 to something like 300 and then run the script, the loop will display

 The number is: 300 

and will continue to print similar lines, with increasing numbers, through

 The number is: 399 

The for Statement

Anything you want to do with a for statement, you can also do with a while statement, but a for statement is often a more efficient method of achieving the same effect. In Listing 6.6, you saw how a variable was initialized outside the while statement, then tested within its expression, and incremented within the code block. The for statement allows you to achieve this same series of events, but in a single line of code. This allows for more compact code and makes it less likely that you will forget to increment a counter variable, thereby creating an infinite loop:

 for (initialization expression; test expression; modification expression) {     // code to be executed } 

By the Way

Infinite loops are, as the name suggests, loops that run without bounds. If your loop is running infinitely, your script is running for an infinite amount of time. This is very stressful on your Web server, and renders the Web page unusable.


The expressions within the parentheses of the for statement are separated by semicolons. Usually, the first expression initializes a counter variable, the second expression is the test condition for the loop, and the third expression increments the counter. Listing 6.8 shows a for statement that re-creates the example in Listing 6.6, which multiplies 12 numbers by 2.

Listing 6.8. Using the for Statement
 1: <?php 2: for ($counter=1; $counter<=12; $counter++) { 3:     echo "$counter times 2 is ".($counter * 2)."<br>"; 4: } 5: ?> > 

Put these lines into a text file called testfor.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 1 times 2 is 2 2 times 2 is 4 3 times 2 is 6 4 times 2 is 8 5 times 2 is 10 6 times 2 is 12 7 times 2 is 14 8 times 2 is 16 9 times 2 is 18 10 times 2 is 20 11 times 2 is 22 12 times 2 is 24 

The results of Listings 6.6 and 6.8 are exactly the same, but the for statement makes the code in Listing 6.8 more compact. Because the $counter variable is initialized and incremented at the beginning of the statement, the logic of the loop is clear at a glance. In line 2, the first expression initializes the $counter variable and assigns a value of 1. The test expression verifies that $counter contains a value that is less than or equal to 12. The final expression increments the $counter variable. Each of these items are found in the single line of code.

When the sequence of script execution reaches the for loop, the $counter variable is initialized and the test expression is evaluated. If the expression evaluates to true, the code block is executed. The $counter variable is then incremented and the test expression is evaluated again. This process continues until the test expression evaluates to false.

Breaking Out of Loops with the break Statement

Both while and for statements incorporate a built-in test expression with which you can end a loop. However, the break statement enables you to break out of a loop based on the results of additional tests. This can provide a safeguard against error. Listing 6.9 creates a simple for statement that divides a large number by a variable that is incremented, printing the result to the screen.

Listing 6.9. A for Loop That Divides 4000 by 10 Incremental Numbers
 1: <?php 2: for ($counter=1; $counter <= 10; $counter++) { 3:     $temp = 4000/$counter; 4:     echo "4000 divided by $counter is... $temp<br>"; 5: } 6: ?> 

In line 2, this example initializes the variable $counter and assigns a value of 1. The test expression in the for statement verifies the value of $counter is less than or equal to 10. Within the code block, 4000 is divided by $counter, printing the result to the browser.

Put these lines into a text file called testfor2.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 4000 divided by 1 is... 4000 4000 divided by 2 is... 2000 4000 divided by 3 is... 1333.33333333 4000 divided by 4 is... 1000 4000 divided by 5 is... 800 4000 divided by 6 is... 666.666666667 4000 divided by 7 is... 571.428571429 4000 divided by 8 is... 500 4000 divided by 9 is... 444.444444444 4000 divided by 10 is... 400 

This seems straightforward enough. But what if the value you place in $counter comes from user input? The value could be a negative number, or even a string. Let's take the first instance, where the user input value is a negative number. Changing the initial value of $counter from 1 to -4 causes 4000 to be divided by 0 when the code block is executed for the fifth time. It is generally not a good idea for your code to divide by zero, as it results in an answer of "undefined." Listing 6.10 guards against this by breaking out of the loop if the value of the $counter variable equals zero.

Listing 6.10. Using the break Statement
 1: <?php 2: $counter = -4; 3: for (; $counter <= 10; $counter++) { 4:     if ($counter == 0) { 5:         break; 6:     } else { 7:         $temp = 4000/$counter; 8:         echo "4000 divided by $counter is... $temp<br>"; 9:     } 10: } 11 ?> 

By the Way

Dividing a number by zero does not cause a fatal error in PHP. Instead, PHP generates a warning and execution continues.


We use an if statement, shown in line 4, to test the value of $counter before attempting mathematical operations using this value. If the value of $counter is equal to zero, the break statement immediately halts execution of the code block, and program flow continues after the for statement (line 11).

Put these lines into a text file called testfor3.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 4000 divided by -4 is... -1000 4000 divided by -3 is... -1333.33333333 4000 divided by -2 is... -2000 4000 divided by -1 is... -4000 

Notice that the $counter variable was initialized in line 2, outside the for statement's parentheses. This method was used to simulate a situation in which the value of $counter is set from outside the script.

Did you Know?

You can omit any of the expressions from a for statement, but you must remember to retain the separation semicolons.


Skipping an Iteration with the continue Statement

The continue statement ends execution of the current iteration but doesn't cause the loop as a whole to end. Instead, the next iteration begins immediately. Using the break statement as we did in Listing 6.10 is a little drastic; with the continue statement in Listing 6.11, you can avoid a divide by zero error without ending the loop completely.

Listing 6.11. Using the continue Statement
 1: <?php 2: $counter = -4; 3: for (; $counter <= 10; $counter++) { 4:     if ($counter == 0) { 5:         continue; 6:     } 7:     $temp = 4000/$counter; 8:     echo "4000 divided by $counter is... $temp<br>"; 9: } 10:?> 

In line 5, we have swapped the break statement for a continue statement. If the value of the $counter variable is equivalent to zero, the iteration is skipped and the next one starts immediately.

Put these lines into a text file called testcontinue.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 4000 divided by -4 is... -1000 4000 divided by -3 is... -1333.33333333 4000 divided by -2 is... -2000 4000 divided by -1 is... -4000 4000 divided by 1 is... 4000 4000 divided by 2 is... 2000 4000 divided by 3 is... 1333.33333333 4000 divided by 4 is... 1000 4000 divided by 5 is... 800 4000 divided by 6 is... 666.666666667 4000 divided by 7 is... 571.428571429 4000 divided by 8 is... 500 4000 divided by 9 is... 444.444444444 

Watch Out!

Using the break and continue statements can make code more difficult to read, because they often add layers of complexity to the logic of the loop statements that contain them. Use these statements with care, or comment your code to show other programmers (or yourself) just what you're trying to achieve with these statements.


Nesting Loops

Loops can contain other loop statements, as long as the logic is valid and the loops are tidy. The combination of such statements is particularly useful when working with dynamically created HTML tables. Listing 6.12 uses two for statements to print a multiplication table to the browser.

Listing 6.12. Nesting Two for Loops
 1: <?php 2: echo "<table border=\"1\" cellpadding=\"4\" cellspacing=\"4\">\n"; 3: for ($y=1; $y<=12; $y++) { 4:     echo "<tr> \n"; 5:     for ($x=1; $x<=12; $x++) { 6:         echo "<td>"; 7:         echo ($x * $y); 8:         echo "</td> \n"; 9:     } 10:     echo "</tr> \n"; 11: } 12: echo "</table>"; 13: ?> 

Before we examine the for loops, let's take a closer look at line 2 in Listing 6.12:

 echo "<table border=\"1\" cellpadding=\"4\" cellspacing=\"4\"> \n"; 

Notice that we have used the backslash character (\) before each of the quotation marks within the string. This is necessary, as it tells the PHP engine that we wish to use the quotation mark character, rather than have PHP interpret it as the beginning or end of a string. If we did not escape the quotation marks, the statement would not make sense to the engine, as it would read it as a string followed by a number followed by another string. Such a construct would generate an error. Also in this line, we use \n to represent a newline character, which will make the source easier to read once it is rendered by the browser.

The outer for statement (line 3) initializes a variable called $y, assigning to it a starting value of 1. This for statement defines an expression that intends to verify that the value of $y is less than or equal to 12, and then defines the increment which will be used. In each iteration, the code block prints a tr (table row) HTML element (line 4) and begins another for statement (line 5). This inner loop initializes a variable called $x and defines expressions along the same lines as for the outer loop. For each iteration, the inner loop prints a TD (table cell) element to the browser (line 6), as well as the result of $x multiplied by $y (line 7). In line 8, we close the table cell. After the inner loop has finished, we fall back through to the outer loop, where we close the table row on line 10, ready for the process to begin again. When the outer loop has finished, the result is a neatly formatted multiplication table. We wrap things up by closing the table on line 12.

Put these lines into a text file called testnestfor.php, and place this file in your Web server document root. When you access this script through your Web browser, it should look like Figure 6.1.

Figure 6.1. Output of testnestfor.php.




Sams Teach Yourself PHP MySQL and Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (4th Edition)
ISBN: 067232976X
EAN: 2147483647
Year: 2003
Pages: 333
Authors: Julie Meloni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net