PHP out of the loop of the "break"

PHP to you on the front of the control loop, you know, when our block to meet certain conditions will be out of the loop, but it is out of the loop or continue to use our break keyword. This chapter will give you on the "break" out of the loop.

 

When the previous lecture PHP loop control statements "while" loop, it has been mentioned that our break up, break the keyword may terminate our current cycle, including while, do ... while, for, foreach, and switch on all within the control statements. Let's look at an example.

Examples of break out of the loop

This example uses a while loop, while behind the conditional expression is true, is an infinite loop. While in the declaration block at a random variable $ tmp, only when the generated random number is equal to 10, it uses the break statement out of the loop codes are as follows: Pingshanyou marble platform

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

header("Content-type:text/html;charset=utf-8");    //设置编码

 

while(true){                                                //使用while循环

    $tmp=rand(1,20);                                        //说明一个随机变量$tmp

    echo $tmp." ";                                          //输出生成的随机数

    if($tmp==10){                                           //判断生成的随机数是否等于10

        echo "<p>变量\$tmp等于10,跳出循环</p>";

        break;                                               //如果等于10,使用break语句跳出循环

    }

}

 

?>

FIG codes results are as follows:

We can not only break statement out of the current cycle, you can also specify several layers out of circulation the following format:

1

break $num

$ Num parameter is specified several layers to get out of the cycle, there will be the following example to illustrate.

Look at the break keywords flow graph:

 

Specifies tier instance bounce cycle

This example has three circular layers, the outermost layer and the while loop is a wireless loop for the middle loop, the innermost loop has two parallel for: First, the program first performs first for loop, when the variable $ i is equal to 7 when, out of the current cycle (a heavy cycle), the second for loop continues, when the second for loop variables $ j equal to 15, directly out of the outermost loop, as follows:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<?php

header("Content-type:text/html;charset=utf-8");    //设置编码

 

while(true){

    for(;;){

        for($i=0;$i<=10;$i++){

            echo $i." ";

            if($i==7){

                echo "<p>变量\$i等于7,跳出一层循环</p>";

                break 1 ;

            }

        }

        for($j=0;$j<=20;$j++){

            echo $j." ";

            if($j==15){

                echo "<p>变量\$j等于15,跳出最外层循环</p>";

                break 3;

            }

        }

 

    }

    echo "不会执行这句话";

}

 

?>

Guess you like

Origin www.cnblogs.com/furuihua/p/12112305.html