break the loopPHP break statement ends execution of the current for, foreach, while, do-while or switch structure.
Syntax:
break NUM;
The NUM is optional,it tells how many nested enclosing structures are to be broken out of. default is 1.
<?php
$arr = array(1,2,3,4);
foreach ($arr as $val) {
if ($val == 3) {
break;
}
echo "$val<br>";
}
?>
Outputs:
1 2
<?php
for($i=1;$i<10;$i++){
for($j=1;$j<10;$j++){
echo "i=".$i.", j=".$j."<br>";
if($j==4){
break;
}
if($i==3 && $j==2){
break 2;
}
}
echo "<br>";
}
?>
Outputs:
i=1, j=1 i=1, j=2 i=1, j=3 i=1, j=4 i=2, j=1 i=2, j=2 i=2, j=3 i=2, j=4 i=3, j=1 i=3, j=2
<?php
$i = 3;
switch ($i) {
case 1:
echo "case 1";
break;
case 2:
echo "case 2";
break;
default:
echo "default";
break;
}
?>
