Home > Article > Backend Development > PHP jump out of foreach / for loop implementation program_PHP tutorial
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
The code is as follows
|
Copy code
|
||||
for($i = 1000;$i > ;= 1 ; $i– ){ | if( sqrt($i) <= 29){
}
http://www.bkjia.com/PHPjc/628984.htmlwww.bkjia.comtruehttp: //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...