Tutorials

PHP Loops

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

Continue and Break

PHP offers two language constructs to break out of your loop: continue and break. "Continue" is used to skip the rest of the instructions in the current iteration of the loop. Let's say you want to count from 1 to 100 but skip printing all the even numbers:

Each iteration of the loop we have a condition to check if $x is evenly divisible by 2. If it is, we skip echoing out $x and move on to the next iteration. Now we could have just as easily done this:

But that's not the point! Besides, continue and break are useful for things much more complex than this. Break works the same way as continue, except that it breaks out of the whole loop, instead of the current iteration.

Both break and continue can take an optional argument for you to specify what level loop to break or continue. This is useful for nested loops, where if you for example have a loop running inside another loop and if some condition is met, you want to exit out of the loop, even the main loop, you can do this:

In this nested loop, we are printing out everything from 1 * 1 to 10 * 10 but we have a condition inside the nested loop to break out of all of the loops if we find an answer that equals 50.

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.