Working with while Loops


Working with while Loops

Another important type of loop is the while loop. Rather than using a loop index, this loop keeps going while a certain condition is true, executing its statement over and over:

 while (expression) statement 

Here, statement can be a compound statement, surrounded in curly braces. This loop will keep going as long as the condition expression remains true. As you can imagine, if you don't want the loop to keep going forever, you have to do something in statement eventually that will make expression false.

Example 2-8, phpwhile.php, shows a while loop. In this case, we'll display the value in a variable as long as it's less than 10note that we double the value in the variable each time through the loop so that the loop will eventually stop, and we assign a value to the variable before beginning so it doesn't start off with a value of 0 (which would mean the loop would never stop).

Example 2-8. Using the while loop, phpwhile.php
 <HTML>     <HEAD>         <TITLE>             Using the while loop         </TITLE>     </HEAD>     <BODY>         <H1>             Using the while loop         </H1>         <?php             $value =1;             while ($value < 10){                 echo "New value:", $value, "<BR>";                 $value *=2;             }         ?>     </BODY> </HTML> 

You can see the results in Figure 2-9; the while loop displays the current value of the variable, doubling it each time through, until that value exceeds 10. Perfect.

Figure 2-9. Using the while loop.


This kind of loop is often used when your loop doesn't have an explicit loop index. For example, when you're reading data from a file, you can use functions to test where you're at in the file whose data you're reading. Here's how it looks in outlinewe open the file and test if we're at the end of the file (these are made-up functions):

 <?php     open_file();     while (not_at_end_of_file()){         .         .         .     } ?> 

If we're not at the end of the file, we read and echo a line from the file. Then we test if we're at the end of the file again, and if so, we quit. Otherwise, we read another line:

 <?php     open_file();     while (not_at_end_of_file()){         $data = read_one_line_from_file();         echo $data;     } ?> 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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