BREAKING MULTIPLE LOOPS IN PHP

Feb 17, 2026

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 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.


AI Assistant

Choose AI provider

Text Tools

Make content clear and easy to read

Have a Question?

Get clear answers based on this content

0/500
Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.