The
break
keyword immediately terminates the current loop.
Similar to the continue
statement, a break
halts execution of a loop. Unlike a continue
statement, however, break
causes the immediate termination of the loop and does not execute the conditional statement again.
$i = 5;
while(true) {
echo 120/$i.PHP_EOL;
$i -= 1;
if ($i == 0) {
break;
}
}
This code will produce
24
30
40
60
120
but will not execute the case where $i
is 0, which would result in a fatal error due to division by 0.
The break statement may also be used to break out of several levels of loops. Such behavior is very useful when executing nested loops. For example, to copy an array of strings into an output string, removing any #
symbols, until the output string is exactly 160 characters
$output = "";
$inputs = array(
"#soblessed #throwbackthursday",
"happy tuesday",
"#nofilter",
/* more inputs */
);
foreach($inputs as $input) {
for($i = 0; $i < strlen($input); $i += 1) {
if ($input[$i] == '#') continue;
$output .= $input[$i];
if (strlen($output) == 160) break 2;
}
$output .= ' ';
}
The break 2
command immediately terminates execution of both the inner and outer loops.