continue

(PHP 4, PHP 5, PHP 7, PHP 8)

continue 在循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。

注意: 在 PHP 中 switch 语句被认为是可以使用 continue 的一种循环结构。 continue 的行为类似于没有传递参数的 break ,但会引发警告,因为这可能是一个错误。 如果 switch 在循环内, continue 2 将会外部循环中的下一个迭代中继续。

continue 接受一个可选的数字参数来决定跳过几重循环到循环结尾。默认值是 1,即跳到当前循环末尾。

<?php
foreach ($arr as $key => $value) {
if (!(
$key % 2)) { // 忽略偶数成员
continue;
}
do_something_odd($value);
}

$i = 0;
while (
$i++ < 5) {
echo
"Outer<br />\n";
while (
1) {
echo
"Middle<br />\n";
while (
1) {
echo
"Inner<br />\n";
continue
3;
}
echo
"This never gets output.<br />\n";
}
echo
"Neither does this.<br />\n";
}
?>

省略 continue 后面的分号会导致混淆。以下例子示意了不应该这样做。

<?php
for ($i = 0; $i < 5; ++$i) {
if (
$i == 2)
continue
print
"$i\n";
}
?>

希望得到的结果是:

0
1
3
4

continue 的更新记录
版本 说明
7.3.0 switchcontinue 语句试图代替 break 语句将会触发 E_WARNING

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top