Membership
Main Menu
Forum Boards
Stats
- 20 tutorials
- 74,815 members
- 734,908 forum posts
- 13 blog posts
Tutorials
PHP Loops
Views: 25163
...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.
