Membership
Main Menu
Forum Boards
Stats
- 18 tutorials
- 72,341 members
- 696,907 forum posts
- 11 blog posts
Tutorials
PHP Loops
Views: 21573
The Do...While Loop
The do..while loop works pretty much exactly the same as the while loop, except that the instruction will always be executed first. The basic syntax looks like this:
initialization
do {
instruction
iteration
} while (condition);
As with the while loop, putting the components in those positions makes it a glorified for loop, and you should use a for loop. Just like the while loop, the power is being able to combine the components and/or make a loop with an undetermined amount of iterations.
If we were to use a do...while loop with the previous database example :
In this example, we're going to run into some problems. Because the instruction comes first, $name['name'] does not exist until after the first iteration of the loop. In my experience, there aren't very many circumstances where a do...while loop is preferred over a while loop. It's really only good for wanting to make a loop where you want the instruction to be executed at least one time, no matter what.
