In PHP, you are probably familiar with the break keyword, which is used to stop a loop.
What many developers donβt realize is that it break can accept a numeric argument. This number tells PHP how many nested loop levels should be terminated.
Consider the following example:
foreach ($firstLoop as $firstItem) {
foreach ($secondLoop as $secondItem) {
foreach ($thirdLoop as $thirdItem) {
if ($this->shouldStop($thirdItem)) {
break 2; // Exit third and second loops
}
}
}
}
What does break 2; do?
-
break 1;(or simplybreak;) stops only the current (innermost) loop. -
break 2;stops two nested loops. -
break 3;would stop three nested loops, and so on.
In this example, break 2; exits:
- The third loop (innermost)
- The second loop
Execution then continues in the first loop.
This is especially useful when working with deeply nested loops, and you need to escape multiple levels once a condition is met.
π₯ Find more real-world coding tips:
Top comments (0)