Tutorials

PHP Loops

by Crayon Violent on Jun 19, 2008 2:46:30 PM

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.

Comments

Again, very nice CV. Only thing i would mention is that it's not strictly true that a for loop requires all 3 parameters. This is a perfectly valid for loop:

As is this:

Of course, they serve no real useful purprose (use a while loop, it's easier to follow) but i had to find something wrong with it :P

1. Ben Smithers on Jun 20, 2008 5:07:40 AM

Ah you are right, but in order for the loops to function properly, they still need to have all the components somewhere. Your first example, while syntactically correct, would in and of itself be an infinite loop. Using your first example, you would have to put the condition and iteration inside the instruction. Example:

I'm glad you pointed that out though : )

2. Crayon Violent on Jun 20, 2008 10:19:46 AM

A concise explanation of loops. Very good.

3. kahratka on Jun 20, 2008 10:32:40 AM
Login or register to post a comment.