0
0
PHPprogramming~5 mins

Break statement with levels in PHP

Choose your learning style9 modes available
Introduction

The break statement stops a loop or switch early. Using levels lets you stop multiple loops at once.

When you want to exit from nested loops quickly.
When a condition inside inner loops means all loops should stop.
When you want to avoid extra checks after finding a result in nested loops.
Syntax
PHP
break; // stops the current loop

break n; // stops n levels of loops, where n is a positive integer

The default break stops only the innermost loop.

Using break with a number lets you jump out of multiple loops at once.

Examples
This stops the loop when $i is 2, so it prints 1 only.
PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    if ($i == 2) {
        break;
    }
    echo $i . " ";
}
?>
This breaks out of both loops when $j is 2, so it prints only "1,1 ".
PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        if ($j == 2) {
            break 2;
        }
        echo "$i,$j ";
    }
}
?>
Sample Program

This program prints the first pair of loop values, then stops both loops immediately when $j equals 2.

PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        if ($j == 2) {
            break 2; // exit both loops
        }
        echo "Loop: $i,$j\n";
    }
}
?>
OutputSuccess
Important Notes

Break with levels only works inside nested loops or switch statements.

Using break with a level higher than the number of loops will stop all loops.

Summary

The break statement stops loops early.

Using break with a number lets you exit multiple loops at once.

This helps avoid extra work when a condition is met inside nested loops.