Tutorials

PHP Loops

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

...And Again And Again

The Iteration
This is where PHP increments the initialization variable. In our example, we do $x++. This is just a shorthand way of doing $x = $x + 1, which is equally valid. it is also equally valid to increment it by something other than 1. It doesn't even have to be a whole number. It can even subtract a number so your loop can "count down."

How you want your loop to count (the increments per loop, counting up or down, etc..) is entirely up to you, and you will base that on what your goal for the instruction is. In this example, we could just as easily start with the ending number and count down to the starting number, subtracting 1 from $x during each iteration of the loop, like so:

On that note, be careful to "phrase" your loop correctly, or you will not get your desired results, or worse, end up with an infinite loop. Consider this loop:

We are telling the loop to start at 100, and while $x is greater than 200, run the instruction. Well the problem is, right out the gate, the condition is false, because 100 is not greater than 200. Our loop will never execute. Or how about this example:

Whoops, we accidentally put the start and finish variables backward. Since we start at 200, our loop will keep iterating as long as it is greater than 100. Each iteration, we add 1 to 200, so the condition will always evaluate as true. The loop will never stop, thus creating an infinite 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.