Web Statistics

break, continue, & goto

You've got to know when to hold 'em.
Know when to fold 'em.
Know when to walk away,
And know when to run - Kenny Rogers

It is here after the discussion of loops ( While/Do Loops & For/Foreach Loops ) that we come to a few controls that are useful inside the loop instance. If you are unfamiliar with these process loop types it would be to your benefit to review them at this time.


The break control, in its simplest explanation, is used to exit the code block at the point where the break is located. This gives logical control to exit from the loop when circumstances are reached. In this situation the loop is terminated and not just the iteration of the loop instance. Below is an example of how the break is commonly used inside a foreach loop.

$arr = array(1,3,5,7);
foreach ($arr as $item)
	if ($item>=5)
	print $item;

What is happening in this example is if, and when, the array element value is greater than, or equal to, 5 the loop exits and the process continues on. If the array element is less than 5 thee code block prints the array element value.

That's pretty cool, but this is not where you see the break control used the most. Remember back when the topic was the switch control? Ya! probably time to go back and look at that. The switch control uses the break at the end of each condition case.


The difference in the continue control from the break control is that while break control exits the loop entirely, the continue control exits the iteration of the loop. The continue control can be used at any point inside a loop.


For the sake of best practices I am abandoning the goto operator/control. Professionally I have not seen its usage in PHP5 in a few years now. If you are interested in learning this control have a look at PHP.net

Up Next

Include, Require, and so on...