For and While Loops
The last language construct I’ll discuss is loops. You’ve already used one, foreach, when managing arrays. The next two types of loops you’ll use are for and while.
The while loop looks like this:
while (condition) {
// Do something.
}
As long as the condition part of the loop is true, the loop will be executed. Once it becomes false, the loop is stopped (Figure 2.23). If the condition is never true, the loop will never be executed. The while loop will most frequently be used when retrieving results from a database, as you’ll see in Chapter 7, “Using PHP with MySQL.”
Figure 2.23. A flowchart representation of how PHP handles a while loop.
The for loop has a more complicated syntax:
for (initial expression; condition ...
Get PHP and MySQL for Dynamic Web Sites: Visual Quickpro Guide, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.