The break Construct
The break
construct immediately terminates the execution of the current loop (for
, while
, do-while
, or foreach
) or the switch
statement. After executing break
, control is passed to the line of code immediately following the interrupted construct.
After the break
command, you can write a number that indicates how many nested constructs should be interrupted (default is 1
).
Syntax
break;
break $level;
Example
Loop interruption when a condition is met:
<?php
for ($i = 0; $i < 5; $i++) {
if ($i == 3) {
break;
}
echo $i;
}
?>
Code execution result:
'012'
Example
Usage in the switch statement:
<?php
$value = 2;
switch ($value) {
case 1:
echo 'One';
break;
case 2:
echo 'Two';
break;
default:
echo 'Other';
}
?>
Code execution result:
'Two'
Example
Interrupting nested loops with level specification:
<?php
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
if ($j == 1) {
break 2; // Interrupts both loops
}
echo $i.$j;
}
}
?>
Code execution result:
'00'