Membership
Main Menu
Forum Boards
Stats
- 18 tutorials
- 72,337 members
- 696,782 forum posts
- 11 blog posts
Tutorials
PHP Loops
Views: 21561
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.
