How to Break/Exit a Loop in PHP?

Problem:

You want to exit a loop when it meets a certain condition before it ends normally.

Solution:

You can end the execution of a loop using break keyword. In the following we’ll see the use of break keyword in few situations-

(1) If you write break keyword inside a loop, the loop will exit as soon as the interpreter finds the keyword. See the example below-

<?php
for($i=1; $i<=10;$i++){
echo $i;
break;
}
?>

Output:
1

How it works:
When the loop runs for the first time, it variable $i enters into the loop with the value 1. And it prints the value 1 in line 3. Then, in the next line, it finds the keyword break and the loop exits at that point. If break was not written there, the loop would print 12345678910.

(2) You can end the loop when it meets a certain condition. See the example below-

<?php
for($i=1;$i<=5;$i++){
echo $i;
if($i == 3) break;
}
?>

Output:
123

How it works:
The loop executes and print the value of variable $i. When the value of $i is 3 the if condition inside the loop fulfilled and the break statement executes and the loop exits.

(3) If a break keyword is surrounded by more then one enclosing structure(ex. loop), you can break any number of enclosing structure mentioning the number after the break keyword. See the following example-

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

[wpdm_file id=162]

Output:
1
12
123

How it works:
When the loops displays the above lines as you see above in the output, the value of the variable $j becomes 3 and meet the if condition in line 5 and executes the break statement. As there are 2 after the break, the interpreter will ends the two enclosing structures at this points. Here the two enclosing structures are the two for loops. If we didn’t use the break keyword above, the program outputs the following-

1
12
123
1234
12345

break keyword can end execution of the following structures – for, foreach, while, do-while and switch.