略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: break

2024-04-17

break

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

break 结束执行当前的 forforeachwhiledo-whileswitch 结构。

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 noteadd a note

User Contributed Notes 2 notes

up
13
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;
  }
?>
up
-23
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>";
}
?>

官方地址:https://www.php.net/manual/en/control-structures.break.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3