Saturday, October 23, 2010

PHP: How to exit a for loop or skip iteration

It seems like quite a few people still don't know how to exit various loops. It's really easy and there are two ways you can do this.

First: when you reach a point where you would like to break out of a loop, it would be an if statement most likely just use command "break" to exit the loop. The "break" command just exits the current loop not all loops if you have them nested. This command works with while loops, for loops, and do..while loops.

Second: whenever you reach a point where you would like to exit the loop you can use a "goto" statement to forces jump script another part of the script on the page. To set it up, you place the command "goto goHere" at the point where you want to stop the loop. Then select the area where you would like the script to continue and place "goHere: " statement. Once the script meets your criteria and reaches the "goto" statement it will skip everything and jump to "goHere: " section and proceed from there.

Now, you can also skip loop iterations whenever necessary. Skipping loop iterations is done using "continue" command. This "continue" command does not return anything just skips an iteration and your loop keeps looping as it was before.

Here is an example of all there commands in one script:

As you can see the loop should cycle until $i is less than 100. The iteration is skipped once it reaches 2 and 4. When iteration reaches 5 it forces the script to the last if statement even though variable i does not equal 10 yet. In that if statement we set the variable i to 98 to let the loop finish quickly.


No comments:

Post a Comment