VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-break-an-outer-loop-with-php/

⇱ How to break an outer loop with PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to break an outer loop with PHP ?

Last Updated : 20 Sep, 2024

In PHP, breaking an outer loop refers to exiting a parent loop from within a nested loop. This can be achieved using the break statement with a numeric argument indicating how many levels of loops to exit. It helps control complex loop flow efficiently.

Using break keyword

In PHP, the break keyword immediately terminates a loop, resuming program execution at the next statement. In nested loops, you can pass a numeric argument to `break` to exit multiple loops, controlling the flow of complex structures efficiently.

Syntax

break number_of_nested_loop_to_terminate;

Parameters: The break keyword followed by a numeric argument which is by default 1. Passing of variables and 0 as a numeric argument is not allowed.

Examples:

break 2; // It terminates second outer loop
break 3; // It terminates third outer loop
break $num; // Variable cannot be used as numeric argument since version 5.4.0
break 0; // 0 is not a valid argument to pass

Below programs illustrate how to break outer loops in PHP:

Example : In this example we demonstrates the use of the break statement with an argument of 2 to exit both the inner while loop and the outer for loop when a specific condition is met.


Output
1 2 3

Example: In this example we searches for a number in a 2D array using nested loops. It uses break 2 to exit both loops when the number is found, ensuring efficient execution.


Output
45 is found in the array

Using goto keyword

The goto keyword in PHP allows jumping to a specific label, bypassing normal flow control. It can be used to break out of nested loops by directing execution to a labeled statement, though its use is generally discouraged due to reduced code readability.

Example : In this example we searches for a number in a 2D array and uses the goto keyword to exit both loops when the number is found, improving loop termination efficiency.


Output
45 is found in the array
Comment