Skip to Main Content
Learning PHP, MySQL, and JavaScript
book

Learning PHP, MySQL, and JavaScript

by Robin Nixon
July 2009
Beginner content levelBeginner
526 pages
14h 24m
English
O'Reilly Media, Inc.
Content preview from Learning PHP, MySQL, and JavaScript

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 the program 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.

Imagining a loop as part of a program highway layout
Figure 4-4. Imagining a loop as part of a program highway layout

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).

Example 4-28. A while loop
<?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 ...

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.
Start your free trial

You might also like

Web Database Applications with PHP and MySQL, 2nd Edition

Web Database Applications with PHP and MySQL, 2nd Edition

Hugh E. Williams, David Lane
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 9780596803605Supplemental ContentErrata Page