Ways to exit from a foreach loop in PHP

In this article, we will focus on the different exit methods from the foreach loop in PHP. Before that, we will discuss what exactly a foreach loop is.

What is a foreach loop in PHP?

In PHP, the foreach loop is the same as the for a loop. But the difference is that the foreach loop can hold the entire array at a time. Hence, it is used in the case of a numeric array as well as an associative array.

The syntax for a foreach loop is,

foreach($array as value)
{
statement(s);
}

In PHP, to break from a  foreach loop, following jumping statements are used-

  • break statement
  • continue statement
  • goto statement

break statement to exit from a foreach loop

The break statement is used to come out of the foreach loop.

The below example illustrates the use of the break statement,



<?php

//given array
$arr=array('roll_1'=>'John','roll_2'=>'Subrat','roll_3'=>'Sumi','roll_4'=>'Jyoti','roll_5'=>'Lucky');

//put a counter
$count = 0;

//declare when you want to break the  execution
$brk_val=3;

foreach($arr as $key => $val) {
    
  echo "Name of $key : $val<br/>"; //Print the value of the Array
    
  $count++; //Increment the counter
    
  if($count==$brk_val) 
    break; //Break the loop when $count=$brk_val
}

?>

Output:-

Name of roll_1 : John
Name of roll_2 : Subrat
Name of roll_3 : Sumi

continue statement to skip the execution of a condition

The continue statement skips the execution for a specific condition from the foreach loop.

The below example illustrates the use of the continue statement,

<?php

//given array
$arr=array('roll_1'=>'John','roll_2'=>'Subrat','roll_3'=>'Sumi','roll_4'=>'Jyoti','roll_5'=>'Lucky');

foreach($arr as $key => $val) 
{
    
  if($val == 'Jyoti') 
    continue ; //skip the array pair when key value=Jyoti
  else
    echo "Name of $key : $val<br/>"; //Print the value of the Array
    
}

?>

Output:-

Name of roll_1 : John
Name of roll_2 : Subrat
Name of roll_3 : Sumi
Name of roll_5 : Lucky

using goto statement in PHP

The goto statement moves the control from one portion to another in the foreach loop.

The below example illustrates the use of the goto statement,

<?php

//given array
$arr=array('roll_1'=>'John','roll_2'=>'Subrat','roll_3'=>'Sumi','roll_4'=>'Jyoti','roll_5'=>'Lucky');

//put a counter
$count = 0;

//declare when you want to break the  execution
$brk_val=3;

foreach($arr as $key => $val) {
    
  echo "Name of $key : $val<br/>"; //Print the value of the Array
    
  $count++; //Increment the counter
    
  if($count==$brk_val) 
    goto l; //Break the loop when $count=$brk_val
}
l:
?>

Output:-

Name of roll_1 : John
Name of roll_2 : Subrat
Name of roll_3 : Sumi

In this way, we can exit from a foreach loop in PHP. If you have any doubts, put a comment below.

See also,

Leave a Reply

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