Loops: For or While?

A few weeks ago I needed some help in my learning process. I’d been exposed to a few different loop types, and googling didn’t provide any answers that seemed terribly concrete. So I asked some geek friends, and got fabulous answers from Shelly at Brass Blogs.

I’m posting them here so they don’t get lost in my email again!

If you know how many times you need to loop, use for. If you need to loop until a certain condition is met, use while.

Stop thinking so existentially XD yes, you’re looping until a condition is met, BUT you know when and exactly where apsaid condition will be. IE you know exactly how many loops you need to make. but if you don’t know how many loops you need to get to said condition, that’s when you use the while. If you need 5 loops, “for” is your command. If you need however many loops it takes until you meet your condition, then “while” is how you go…it just keeps rolling until it hits that flag. If it helps, think “for : numerical” and “while: Boolean”. Make sense?

..ert, and “what happens if I use the wrong one?” Nothing, really. They both pretty much do the same thing. In smaller situations, it probably won’t matter. But if you want it to scale, then you’ll want to use the rut one, because it’s *possible* you’ll cause too much server load. But we’re getting into nickel-and-diming here. The server load isn’t really all that large (unless you’re doing something astronomically huge). It’s just *simpler* to use a “for” loop when you’re working numerical. For example, say you wanted to count the loops. Using a for loop, you can just echo $i and be done. Which “while”, you’ll have to add in extra variables ($count=0; $count++;) so really, the difference is sort of like grammar. Use the Oxford comma, or not? if you’re a *purist* it will REALLY matter. But for the most part it doesn’t, not really.

Thanks again to Shelly!