The while Statement


The while Statement

 while (expr) statement 

The while loop is the simplest type of loop in PHP. It tells PHP to execute statement (which could be a compound statement) repeatedly, as long as expr evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement, execution will not stop until the end of the iteration. If the while expression evaluates to FALSE from the very beginning, the nested statement won't even be run once.

As with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces:

 <?php     $loop_index = 1;     while ($loop_index <= 10) {         echo $loop_index++;     } ?> 

This example uses a loop index, $loop_index, but you don't have to use a loop index at all in a while loop. For example, some PHP functions, such as feof (which returns TRUE when you're at the end of a file), are designed to be used in while loops. Here's an example:

 <?php     $handle = fopen("file.txt", "r");     while (!feof($handle)){         $text = fgets($handle);         echo $text, "<BR>";     } ?> 



    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