DEV Community

Mahmoud Ramadan
Mahmoud Ramadan

Posted on

Breaking Multiple Loops in PHP πŸ”

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
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

What does break 2; do?

  • break 1; (or simply break;) 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:

  1. The third loop (innermost)
  2. 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)