PHP 简明教程

PHP continue 语句

1. PHP continue 语句

PHP 中的 continue 语句用于跳过循环中当前的迭代操作,并直接进入下一轮迭代。

continue 语句可用于以下几种循环结构中:

  • for 循环
  • while 循环
  • do...while 循环
  • foreach 循环

2. 在 for 循环中使用 continue

continue 语句可以跳过 for 循环中的当前迭代,并继续执行下一次迭代。

示例

当变量 $x 等于 4 时跳过本次执行,并进入下一次迭代:

for ($x = 0; $x < 10; $x++) {
  if ($x == 4) {
    continue;
  }
  echo "The number is: $x <br>";
}

3. 在 while 循环中使用 continue

continue 语句可以跳过 while 循环中的当前迭代,并继续执行下一次迭代。

示例

当变量 $x 等于 4 时跳过本次执行,并进入下一次迭代:

$x = 0;
while($x < 10) {
  if ($x == 4) {
    // 务必记得在此处处理计数器,否则可能导致死循环
    $x++; 
    continue;
  }
  echo "The number is: $x <br>";
  $x++;
}

(注意:在 while 循环中使用 continue 时,如果更新计数器的代码在 continue 之后,一定要在触发 continue 前先进行计数器步进,以防陷入死循环!此段逻辑为常见易错点。)

4. 在 do...while 循环中使用 continue

continue 语句可以跳过 do...while 循环中的当前迭代,并继续执行下一次迭代。

示例

当变量 $i 等于 3 时跳过本次执行,并移动到下一轮迭代:

$i = 0;
do {
  $i++;
  if ($i == 3) continue;
  echo $i;
} while ($i < 6);

5. 在 foreach 循环中使用 continue

continue 语句可以跳过 foreach 循环中的当前迭代,并继续执行下一次迭代。

示例

如果数组元素 $value 的值是 "blue",则跳过该次执行并进入下一轮:

$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
  if ($value == "blue") continue;
  echo "$value<br>";
}