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. 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 6, “Using PHP and MySQL.”

The for loop has a more complicated syntax:

for (initial expression; condition; closing expression) {
   // Do something.
}

Upon first executing the loop, the initial expression ...

Get PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide 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.