Php jump out of the foreach/for Loop Implementation Program

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.