Break and Continue Statement in PHP

Break Statement

PHP break statement breaks the execution of the current for, while, dowhile, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only.

The break keyword immediately ends the execution of the loop or switch structure. It breaks the current flow of the program at the specified condition and program control resumes at the next statements outside the loop.

The break statement can be used in all types of loops such as while, dowhile, for, foreach loop, and also with switch case.

Example: Let's see a simple example to break the execution of for loop if value of i is equal to 5.

<?php
	for($i=1; $i<=10; $i++){
		echo "$i <br/>";
		if($i==5){
			break;
		}
	}
?>

Continue Statement

The PHP continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.

The continue statement is used within looping and switch control structure when you immediately jump to the next iteration. The continue statement can be used with all types of loops such as - for, while, do-while, and foreach loop.

The continue statement allows the user to skip the execution of the code for the specified condition.

Example: In the following example, we will print only those values of i and j that are same and skip others.

<?php
	//outer loop
	for ($i=1; $i<=3; $i++) {
		//inner loop
		for ($j=1; $j<=3; $j++) {
			if (!($i == $j) ) {
				continue; //skip when i and j does not have same values
			}
		echo $i.$j;
		echo "</br>";
		}
	}
?>

Output

11
22
33