Tutorials

PHP Loops

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

What is a Loop?

Looping is simply a way for you to reduce the amount of code and/or content you have to write out. The idea is that you have something you have to do, or some content you have to show, and instead of just "writing it all out," you find a pattern to it - a common denominator - and let PHP execute the code or generate the content piece by piece using that pattern, based on a condition.

A condition is a way of letting PHP know how many times to run your loop, or when to stop running your loop. The ability to take a condition and execute a set of instructions over and over as long as that condition is true is one of the basic cornerstones of programming.

To demonstrate how loops work, we will use a "for" loop to solve the following example problem:

"Joe wants to be able to take a range of numbers and find out how many numbers are divisible by a certain number, within that range of numbers. "

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.