Break and Continue

Break and Continue are designed to provide a third way of working with conditions in loops. Imagine a situation where there was a particular variable that you were listening for that needed acting on – such as applying further validation or cleaning up. This condition does not relate to the original condition as stated in the loop. That is where continue can help.

Break does the same thing but instead of applying further logic within the loop it breaks out of the loop all together. For example if you came across an exception that rendered the rest of the logic useless then breaking out of the loop might be a preferred option.

Continue in action

    /*Continue statement is used in loops to skip the current iteration and move to the next iteration.*/
    /*This example gives scores for a game but not for stage 4*/
	
    $levels = array(50, 110, 130, 71, 203);
    $total = count($levels);

	for ($i=0; $i<$total; $i++) {
		if ($i == 3) {
			echo "This is level 3 - do something here!";
			continue;
		}
		echo 'Stage '.($i+1).' Score: '.$levels[$i].'
'; }

Break in action

$arr = array('cherry', 'lemons', 'oranges', 'melons', 'jackpot', 'bullion');
while (list(, $val) = each($arr)) {
    if ($val == 'jackpot') {
        break;    
    }
    echo "$val
\n"; }

Caution! Be careful about relying on break and continue statements too much. If you find yourself getting into the habit of using them often you may need to review how you are storing your data! It is always good practice to allow your loop to run its full course – if not you could have memory leaks occurring in your application and compromise logic further down the chain. Use with care and only as a last resort.

If you find yourself getting into the habit of using them often you may need to review how you are storing your data! It is always good practice to allow your loop to run its full course…

No Comments

Post a Comment