Working with do...while Loops


Working with do...while Loops

Besides while loops, you can also use do...while loops in PHP. These loops are just like while loops, except that the condition is checked at the end of the loop, not the beginning:

 do     statement while (expression)  

Here's what the while loop example in the previous chunk would look like as a do...while loop instead:

 <?php     $value =1;     do{         echo $value, "<BR>";         $value *=2;     } while ($value < 10); ?> 

The difference between while loops and do...while loops is where the condition is testedat the beginning or the end of the loop. That can make a big difference. For example, if the condition is false before the loop even starts, a while loop wouldn't even execute once. Here's an example where the condition is false from the very beginning, so this script doesn't echo anything:

 <?php $value =20; while ($value < 10){     $value *=2;     echo $value, "<BR>"; } ?> 

However, in a do...while loop, the condition is tested at the end, so this script does echo 20 in a browser:

 <?php $value =20; do{     echo $value, "<BR>";     $value *=2; } while ($value < 10); ?> 



    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