Php 简明教程

PHP - Break Statement

PHP 中的 break 语句和 continue 语句统称为“循环控制语句”。PHP 中的任何类型的循环( forwhiledo-while )都被设计为按照所使用的测试条件运行一定次数的迭代。循环块中的 break 语句将程序流带到块外部,放弃可能剩余的其他迭代。

The break statement along with the continue statement in PHP are known as "loop control statements". Any type of loop (for, while or do-while) in PHP is designed to run for a certain number of iterations, as per the test condition used. The break statement inside the looping block takes the program flow outside the block, abandoning the rest of iterations that may be remaining.

break 语句通常有条件地使用。否则,循环将终止而不完成第一次迭代。

The break statement is normally used conditionally. Otherwise, the loop will terminate without completing the first iteration itself.

syntax 中 break 语句如下所示:

The syntax of break statement is as follows −

while(expr){
   if (condition){
      break;
   }
}

以下 flowchart 说明 break 语句的工作原理:

The following flowchart explains how the break statement works −

php break statement

Example

以下 PHP 代码展示了在循环中使用 break 的一个简单示例。 while 循环预期执行十次迭代。但是,当计数器超过 3 时,循环中的 break 语句终止循环。

The following PHP code is a simple example of using break in a loop. The while loop is expected to perform ten iterations. However, a break statement inside the loop terminates it when the counter exceeds 3.

<?php
   $i = 1;

   while ($i<=10){
      echo "Iteration No. $i \n";
      if ($i>=3){
         break;
      }
      $i++;
   }
?>

它将生成以下 output

It will produce the following output

Iteration No. 1
Iteration No. 2
Iteration No. 3

可以在 break 关键字的前面指定一个可选的数字参数。这在嵌套循环构造中特别有用。它会说明要中断多少个嵌套的包围结构。默认值为 1,只会中断直接的包围结构。

An optional numeric argument can be given in front of break keyword. It is especially useful in nested looping constructs. It tells how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.

Example

以下示例包含三个嵌套循环:一个 for 循环,其中有一个 while 循环,而 while 循环又包含一个 do-while 循环。

The following example has three nested loops: a for loop inside which there is a while loop which in turn contains a do-while loop.

最里层的循环执行 break 。其前面的数字“2”会将控制从当前作用域传出至 for 循环,而不是直接的 while 循环。

The innermost loop executes the break. The number "2" in front of it takes the control out of the current scope into the for loop instead of the immediate while loop.

<?php
   for ($x=1; $x<=3; $x++){
      $y=1;
      while ($y<=3){
         $z=1;
         do {
            echo "x:$x y:$y z:$z \n";
            if ($z==2){
               break 2;
            }
            $z++;
         }
         while ($z<=3);
         $z=1;
         $y++;
      }
   }
?>

它将生成以下 output

It will produce the following output

x:1 y:1 z:1
x:1 y:1 z:2
x:2 y:1 z:1
x:2 y:1 z:2
x:3 y:1 z:1
x:3 y:1 z:2

请注意,每当“z”的值变为 2 时,程序就会中断“y”循环。因此,“y”的值始终为 1。

Note that each time the value of "z" becomes 2, the program breaks out of the "y" loop. Hence, the value of "y" is always 1.