PHP jump out of foreach / for loop implementation program_PHP tutorial

WBOY
Release: 2016-07-13 17:14:35
Original
1010 people have browsed it

There are several ways to break out of loops in PHP. One is to use goto and the other is to use PHP's new feature goto command. Let me introduce it below.

break is used in the various loops and switch statements mentioned above. Its function is to jump out of the current grammatical structure and execute the following statements. The break statement can take a parameter n, which represents the number of layers to jump out of. If you want to jump out of multiple loops, you can use n to represent the number of layers to jump out of. If there is no parameter, the default is to jump out of the current loop

//The current loop of php is 1, and the loop increases from the inside to the outside. The default break is 1, for example, jumping out of the second layer of the loop

 代码如下 复制代码
for ($i=0;$i<3;$i++){
foreach (array(1,2,3) as $val){
foreach (array(1,2,3) as $val){
echo "1层循环
"; 
            break 2;  //跳出第2层循环        
        }
        echo "2层循环
";
    }
    echo "3层循环
";
}

//Result:
//1 layer loop
//3-layer loop
//1 layer loop
//3-layer loop
//1 layer loop
//3-layer loop

goto
Goto is actually just an operator. Like other languages, the abuse of goto is not encouraged in PHP. Abuse of goto will cause a serious decrease in the readability of the program. The function of goto is to jump the execution of the program from the current position to any other position. goto itself does not have the function of ending the loop, but its jump position allows it to be used as a way to jump out of the loop. However, PHP5.3 and above have stopped supporting goto, so you should try to avoid using goto.
The following is an example of using goto to break out of a loop

if( sqrt($i) <= 29){ goto a;
The code is as follows
 代码如下 复制代码
for($i = 1000;$i >= 1 ; $i– ){
if( sqrt($i) <= 29){
goto a;
}
echo “$i”;
}
a:
echo” this is the end”;
Copy code

for($i = 1000;$i > ;= 1 ; $i– ){
} echo “$i”;

}

a: The example uses goto to break out of the loop. This example is used to detect those numbers within 1000 whose square root is greater than 29
http://www.bkjia.com/PHPjc/628984.htmlwww.bkjia.com
truehttp: //www.bkjia.com/PHPjc/628984.htmlTechArticleThere are several ways to break out of loops in php, one is to use goto and the other is to use php's new feature goto Command, let me introduce it below. break is used in the various loops mentioned above...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template