How to Break the nested loop in PHP

The break statement is used to ends the execution of the current loop or switch case statement in PHP.

But when working with nested loops and wants to exit out from all or some of the outer loops. For this, you need to pass numeric value following with break statement.

In this tutorial, I show how to out from two inner loops and n number of nested loop.

How to Break the nested loop in PHP


Contents

  1. Out from two for loop
  2. Out from n number of nested loop
  3. Conclusion

 

1. Out from two for loop

The break statement takes an optional numeric value its default value is 1. This represents the number of loops to terminate.

For out from two inner loops pass 2 with a break statement from your inner loop when the particular condition is TRUE.

Syntax –

break 2;

Example

<?php 

 for($i=0;$i<5;$i++){

  for($j=0;$j<3;$j++){

   if($i == 3){
    break 2;
   }
 
  }
 
}
echo 'i = '.$i;
?>

Output

i = 3

You can do the same with any other loops – foreach, while, do-while.


 

2. Out from n number of nested loop

Same as above you can break any number of loops from your inner loop.

Syntax –

break n;

Here, n is the number of outer loops you want to out.

Example

<?php
 ## for Loop1
 for($i=0;$i<5;$i++){
  ## for Loop2
  for($j=0;$j<3;$j++){
   ## for Loop3
   for($k=0;$k<3;$k++){
    ## for Loop4
    for($a=0;$a<4;$a++){

      if( $i == 3 ){
       break 4;
      }

    }
 
   }
 
  }
 
}
echo 'i = '.$i;

?>

Here, I am using the break to terminate 4 for loops.

Output

i = 3

 

3. Conclusion

When you are using nested loop within your program in this you can use it to terminate your loop when specified condition is TRUE.

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *