The break
statement is a control statement in PHP that allows you to exit a loop or switch statement early. It is particularly useful for terminating a loop when a certain condition is met, or for breaking out of a switch statement when a matching case is found.
The syntax for the break
statement in PHP is as follows:
break;
The break
statement can be used inside any type of looping statement, including while
loops, do...while
loops, for
loops, and foreach
loops. It can also be used inside a switch
statement to exit the switch and continue with the next statement after the switch.
Here is an example of using the break
statement to exit a for
loop early:
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break;
}
echo $i . "\n";
}
This loop will output the numbers 1 through 4, then exit the loop when $i
becomes 5. The break
statement causes the loop to terminate immediately, and control is passed to the next statement after the loop.
You can also use the break
statement with a label to exit a nested loop or a loop that is not the innermost loop. A label is simply an identifier followed by a colon, placed before the loop statement.
Here is an example of using a label and the break
statement to exit a nested loop:
outer:
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
if ($i == 2 && $j == 2) {
break outer;
}
echo $i . "," . $j . "\n";
}
}