Page 98 - Beginning PHP 5.3
P. 98
Part II: Learning the Language
First a variable, $widgetsLeft , is created to record the number of widgets in stock ( 10 ). Then the while
loop works through the widgets, “ selling ” them one at a time (represented by decrementing the
$widgetsLeft counter) and displaying the number of widgets remaining. Once $widgetsLeft reaches
0 , the expression inside the parentheses ( $widgetsLeft > 0 ) becomes false , and the loop exits.
Control is then passed to the echo() statement outside the loop, and the message “ We ’ re right out of
widgets! ” is displayed.
To see this example in action, save the code as widgets.php in your document root folder and run the
script in your browser. You can see the result in Figure 4 - 2 .
Figure 4-2
Testing at the End: The do . . . while Loop
Take another look at the while loop in the previous example. You ’ ll notice that the expression is tested at
the start of the loop, before any of the code inside the braces has had a chance to run. This means that, if
$widgetsLeft was set to 0 before the while statement was first run, the expression would evaluate to
false and execution would skip to the first line after the closing brace. The code inside the loop would
never be executed.
Of course, this is what you want to happen in this case; you can ’ t sell someone a widget when there are
no widgets to sell! However, sometimes it ’ s useful to be able to run the code in the loop at least once
before checking the expression, and this is exactly what do...while loops let you do. For example, if
the expression you ’ re testing relies on setting a variable inside the loop, you need to run that loop at least
once before testing the expression.
Here ’ s an example of a do...while loop:
< ?php
$width = 1;
$length = 1;
do {
$width++;
60
9/21/09 8:52:09 AM
c04.indd 60 9/21/09 8:52:09 AM
c04.indd 60