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, if the parameter is not included, the loop jumps out.
Example
| The Code is as follows: |
Copy code |
$ Array = array (1, 2, 3, 4, 5, 6 ); For ($ I = 0; $ I <10; $ I ++ ){ Foreach ($ array as $ key) { Echo $ key; If ($ key = 2 ){ Break 2; } } } |
Example
| The Code is as follows: |
Copy code |
<? Php // Set encoding to UTF-8 to avoid Chinese garbled characters Header ('content-Type: text/html; charset = UTF-8 '); // Execute a nested loop. The outer loop is 3 times, and the inner loop is 2 times. When the outer loop is executed for 2nd times, the break jumps out without executing its inner loop. For ($ I = 0; $ I <3; $ I ++ ){ Echo 'outer loop '. $ I.' Start <br/> '; For ($ j = 0; $ j <2; $ j ++ ){ If ($ I = 1 ){ Break; } Echo 'inner loop '. $ I.'-'. $ j.' <br/> '; } Echo 'outer loop '. $ I.' ended <br/> '; } ?> |
The output page of the above Code is as follows:
The outer loop starts with 0.
Inner Loop 0-0
Inner Loop 0-1
Outer Loop 0 ends
Outer Loop 1 starts
Outer Loop 1 ends
Outer Loop 2 starts
Inner Loop 2-0
Inner Loop 2-1
Outer Loop 2 ends
The above code is easy to understand. break is used to jump out of the loop at the current level. However, unlike programming languages such as Java, in PHP, we can also follow the keyword break with a number, which indicates the number of loop layers to jump out, in this way, you can use a break statement to directly jump out of multiple loops. For example:
| The Code is as follows: |
Copy code |
<? Php // Set encoding to UTF-8 to avoid Chinese garbled characters Header ('content-Type: text/html; charset = UTF-8 '); // Execute a nested loop. The outer loop is 3 times, and the inner loop is 2 times. When the outer loop is executed for 2nd times, use break 2 to jump out of the 2-layer loop. For ($ I = 0; $ I <3; $ I ++ ){ Echo 'outer loop '. $ I.' Start <br/> '; For ($ j = 0; $ j <2; $ j ++ ){ If ($ I = 1 ){ Break 2; // use break 2 to jump out of a 2-layer Loop } Echo 'inner loop '. $ I.'-'. $ j.' <br/> '; } Echo 'outer loop '. $ I.' ended <br/> '; } ?> |
The output PAGE result of the sample code is as follows:
The outer loop starts with 0.
Inner Loop 0-0
Inner Loop 0-1
Outer Loop 0 ends
Outer Loop 1 starts
Therefore, in PHP, we can use break to keep up with the specified number to directly jump out of the loop of the specified number of layers.
Note: The number followed by break can only be a positive integer and cannot exceed the number of actually exclusive cycles. Otherwise, a Fatal Error is reported ).