Cases
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; } } } |
Cases
The code is as follows |
Copy Code |
<?php //Set encoding to UTF-8 to avoid Chinese garbled header (' Content-type:text/html;charset=utf-8 '); Execute nested loops, outer loop 3 times, inner layer cycle 2 times. When the outer loop is performed to the 2nd time, use the break to jump out and not perform the inner layer 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. ' End <br/><br/> '; } ?> |
The output page results for the above code are as follows:
Outer Loop 0 Start
Inner Layer Cycle 0-0
Inner Layer Cycle 0-1
Outer Loop 0 End
Outer Loop 1 Start
Outer Loop 1 End
Outer Loop 2 Start
Inner Layer Cycle 2-0
Inner Layer Cycle 2-1
Outer Loop 2 End
The code above is easy to understand, and break is used to jump out of the current level of loops. However, unlike Java and other programming languages, in PHP, we can also follow the keyword break followed by a number, which represents the number of loops to jump out of the layer, so you can use a break statement, jump out of multiple loops. For example:
The code is as follows |
Copy Code |
<?php Set encoding to UTF-8 to avoid Chinese garbled Header (' Content-type:text/html;charset=utf-8 '); Execute nested loops, outer loop 3 times, inner layer cycle 2 times. When the outer loop is performed to the 2nd time, use break 2 to jump out of the 2-tier 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 2-tier loops } Echo ' inner loop '. $i. '-'. $j. ' <br/> '; } echo ' outer loop '. $i. ' End <br/><br/> '; } ?> |
The results of the above sample code output are as follows:
Outer Loop 0 Start
Inner Layer Cycle 0-0
Inner Layer Cycle 0-1
Outer Loop 0 End
Outer Loop 1 Start
Therefore, in PHP, we can use the break followed by the specified number, to jump directly out of the specified layer of the loop.
Note: The number followed by the break can only be a positive integer and cannot exceed the number of loops that can actually jump out. Otherwise, you will report fatal errors (Fatal error).