PHP Tutorial Tutorials - PHP break the loop

PHP break the loop

PHP 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 break: use the numeric argument

<?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 Break: in switch statement

<?php
$i = 3;
switch ($i) {
    case 1:
        echo "case 1";
        break;
    case 2:
        echo "case 2";
        break;
    default:
        echo "default";
        break;
}
?>
Date:2019-10-01 02:40:05 From:www.Lautturi.com author:Lautturi