PHP Break Statement

In this tutorial, you will learn how to use a break statement in PHP to come out from a loop.


PHP break statement breaks the execution of current loops like while, do-while, for, foreach prematurely. If you specify break keyword in the inner loop, it will break the execution of the inner loop only.

The break statement breaks the execution of a loop or switch structure immediately.

PHP break statement can be used with all kinds of loop such as while, do-while, for, foreach or even with switch cases.

PHP break statement Syntax

loop { //any kinds of loop or switch case
statement; 
break;
}

Example: inside loop

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

Output

1
2
3
4
5

Example: inside inner loop

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

Output

1 1
1 2
2 1
2 2
3 1
3 2
4 1
4 2
5 1
5 2

Please get connected & share!

Advertisement