Looping
One of the great things about computers is that they can repeat calculating tasks quickly and tirelessly. Often you may want a program to repeat the same sequence of code again and again until something happens, such as a user inputting a value or reaching a natural end. PHP’s various loop structures provide the perfect way to do this.
To picture how this works, take a look at Figure 4-4. It is much the same
as the highway metaphor used to illustrate if statements, except that the detour also has a
loop section that—once a vehicle has entered—can be exited only under the
right program conditions.

while Loops
Let’s turn the digital car dashboard in Example 4-26 into a loop that continuously
checks the fuel level as you drive using a while loop (Example 4-28).
<?php
$fuel = 10;
while ($fuel > 1)
{
// Keep driving ...
echo "There's enough fuel";
}
?>Actually, you might prefer to keep a green light lit rather than
output text, but the point is that whatever positive indication you wish
to make about the level of fuel is placed inside the while loop. By the way, if you try this
example for yourself, note that it will keep printing the string until
you click the Stop button in your browser.
Note
As with if statements, you will notice that curly braces are required to hold the statements inside the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access