Tutorials

PHP Loops

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

Raspberry Red, Lemony Lemon, Orangey Orange!

Tucan Sam isn't the only dude offering different kinds of loops. PHP offers four different ways to reiterate pieces of code:

- The while loop
- The do...while loop
- The for loop
- The foreach loop

In principle, each kind of loop has the same basic components and does the same basic thing, but their nuances make it possible to write your code more efficiently, depending on your circumstance. The nuances in the loops are being able to put the loop's components in different orders, or even combining components of the loop.

Changing the order of the components is important to know, because this can and will change the outcome of your loop. For example, some loops or orders will execute the instruction first, then check the condition, so you will always get at least one iteration of the loop.

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.