There are several methods to jump out of the loop in php, one is to use goto, and the other is to use the new php goto command. I will introduce it below.
Break is used in various loops and switch statements mentioned above. Its role is to jump out of the current syntax structure and execute the following statements. The break statement can contain a parameter n, indicating the number of layers that exit the loop. To jump out of multiple loops, you can use n to represent the number of layers that exit the loop.
// The current php loop is 1, and the loop increases sequentially from the inside to the outside. The default break is 1, for example, jumping out of the 2nd-layer Loop
The Code is as follows: |
Copy code |
For ($ I = 0; $ I <3; $ I ++ ){ Foreach (array (1, 2, 3) as $ val ){ Foreach (array (1, 2, 3) as $ val ){ Echo "1-layer loop <br/> "; Break 2; // jump out of the 2nd-layer Loop } Echo "2-layer loop <br/> "; } Echo "Layer 3 Loop <br/> "; }
|
// Result:
// Layer-1 Loop
// Layer-3 Loop
// Layer-1 Loop
// Layer-3 Loop
// Layer-1 Loop
// Layer-3 Loop
Goto
Goto is actually just an operator. Like other languages, PHP does not encourage abuse of goto. Misuse of goto will cause serious reduction in program readability. The role of goto is to jump the execution of the program from the current position to any other position. The goto itself does not have the function of stopping the loop, however, its jump position can be used as a jump out loop. However, PHP5.3 and later versions do not support goto, so avoid using goto as much as possible.
The following is an example of using the goto jump out of the loop.
The Code is as follows: |
Copy code |
For ($ I = 1000; $ I >=1; $ I -){ If (sqrt ($ I) <= 29 ){ Goto; } Echo "$ I "; } A: Echo "this is the end "; |
In this example, goto is used to jump out of a loop. In this example, the square root of a number greater than 29 is detected within 1000.