Loops

So far we’ve looked at decisions a script can make about which code to execute. Scripts can also decide how many times to execute a block of code. Loop statements enable you to achieve repetitive tasks. Almost without exception, a loop continues to operate until either a condition is achieved or you explicitly choose to exit the loop.

The while Statement

The while statement looks similar in structure to a basic if statement:

while ( expression ) {
   // do something
}

As long as a while statement’s expression evaluates to true, the code block is executed repeatedly. Each execution of the code block in a loop is often called an iteration. Within the block, you usually change something that affects the while statement’s expression; otherwise, ...

Get Sams Teach Yourself PHP in 24 Hours, Third 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.