break
(PHP 4, PHP 5, PHP 7, PHP 8)
break
结束执行当前的
for
、foreach
、while
、do-while
、switch
结构。
break
接受一个数字的可选参数,决定跳出几重循环。
默认值是 1
,仅仅跳出最近一层嵌套结构。
<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
if ($val == 'stop') {
break; /* 也可以在这里写 'break 1;'。 */
}
echo "$val<br />\n";
}
/* 使用可选参数 */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* 只退出 switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* 退出 switch 和 while 循环 */
default:
break;
}
}
?>
add a note
User Contributed Notes 2 notes
ei dot dwaps at gmail dot com ¶
1 year ago
You can also use break with parentheses: break(1);
Note:
Using more nesting level leads to fatal error:
<?php
while (true) {
foreach ([1, 2, 3] as $value) {
echo 'ok<br>';
break 3; // Fatal error: Cannot 'break' 3 levels
}
echo 'jamais exécuter';
break;
}
?>
mparsa1372 at gmail dot com ¶
1 year ago
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when x is equal to 4:
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
备份地址:http://www.lvesu.com/blog/php/control-structures.break.php