Categories

Articles in Basics Category

Break Statement

Break statement is used to get out of running loops. It’s also used in Switch Case control structures to stop execution of next case statements.

Think that you have to make a sum using array elements and the total sum shouldn’t be greater than 300, then you can make the sum using a Foreach loop and a break statement as below.

$amounts = array(45, 18, 73, 154, 90);
$sum = 0;

foreach ($amounts as $value) {

	if (($sum+$value) > 300) {
		break;
	} else {
		$sum = $sum + $value;
	}	

}

echo 'Sum is '.$sum; // Would print Sum is 290

Think that your check is inside a nested loop (say two levels) and if the check is true then you want to get out of the whole nested loop. Then you can give the number of levels it needs to break up as below.

break(2);

If you run following Switch Case expecting it would print Value is 50 in the web browser then it won’t happen.

$value = 50;

switch ($value) {

	case 50:
		echo 'Value is 50 <br />';

	case 70:
		echo 'Value is 70 <br />';

	case 90:
		echo 'Value is 90 <br />';

}

It would actually execute all three case statements and print following three lines.

Value is 50
Value is 70
Value is 90

The reason is it’s required to have a break statement at the end of each case code block (No need to have at last one but having it brings no harm) to prevent the next case block being executed. So, above code segment should be corrected as below.

switch ($value) {

	case 50:
		echo 'Value is 50 <br />';
		break;

	case 70:
		echo 'Value is 70 <br />';
		break;

	case 90:
		echo 'Value is 90 <br />';
		break;

}

Not having break statements doesn’t make any PHP warning or error so forgetting a break statement can put you in a mess when it comes to debugging. However there can be situations that you may want to omit break statement on purpose. Check Switch Case for such an example.

Where to Head from Here...
Share with Your Peers...

We Value Your Feedback...

We love to hear what you think about this article. Please provide your opinion, suggestions and improvements using following form. Note that submitted feedback is not displayed but we will get back to you if it needs a reply.