How to break and continue forEach loop in PHP - onlyxcodes

Wednesday 22 November 2023

How to break and continue forEach loop in PHP

One popular PHP construct for iterating over arrays and objects is the foreach loop. It enables you to operate on and access every piece of the collection in turn.


But, there are times when you might have to end the loop early or go to the next iteration without finishing the current one. The break and continue statements are used in this case.


We will explain methods for breaking and continuing the forEach loop in this post, along with some explanations and examples.


how to break and continue foreach loop in php

Basics of forEach Loop

Let's revisit the fundamentals of the PHP foreach loop before delving into the specifics of loop control. 


Processing form submissions, managing data collected from a database, and iterating through arrays of user input are some cases where the forEach loop thrives.


Given its simple syntax, it is a well-liked option for iterating over arrays and running a block of code for every element.


foreach ($array as $value) 
{
	// Code to be executed for each $value
}

Example:


<?php

$countries = ['usa', 'uk', 'germany', 'australia'];

foreach ($countries as $country) 
{
   echo $country . ' ';
}

?>

Output:


usa uk germany australia

Breaking the foreach Loop

Introducing the Break Statement:


PHP's break statement is used to terminate the forEach loop before it's finished. The control moves to the next phrase outside the loop as soon as it is faced, exiting the loop instantly. 


When you need to break out of a loop according to a particular criteria, this is helpful.


Consider note of the following code, for instance:


The loop in this example prints each number to the console as it iterates through the $numbers array.


But the loop exits instantly when the $num value hits 3. This is because the break statement is met. Consequently, the only visible numbers are 1 and 2.


<?php

$numbers = [1, 2, 3, 4, 5];

foreach ($numbers as $num) 
{
	if ($num === 3) 
	{
		break;
	}
	
	echo "Number: $num <br>";
}

?>

Output:


Number: 1
Number: 2

Continuing the forEach Loop

On the flip side, the continue statement moves on to the next iteration of the foreach loop and omits the leftover code from the current iteration. 


When you wish to specifically omit any variables or conditions from the loop's processing, this is helpful.


Take a look at this example:


Here, the loop prints each word to the console as it iterates through the $fruits array. 


However, the "continue" statement is reached when the length of the current word ($fruit) reaches 5, which results in the remaining code in that iteration being skipped. 


This means that only the words "banana", "orange", and "strawberry" that have a length of 5 are shown.


<?php

$fruits = ["apple", "banana", "orange", "grape", "strawberry"];

foreach ($fruits as $fruit) 
{
	if (strlen($fruit) === 5) 
	{
		continue;
	}
   
	echo "$fruit <br>";
}

?>


Output:


banana
orange
strawberry

Within nested loops, the break and continue statements are also useful 


The "break" statement will only end the current nested loop and not the entire loop structure when used within nested loops. 


Likewise, the "continue" statement will only skip the code that is still present in this iteration of the nested loop, not the entire loop structure.


How to break the nested loop in PHP

In PHP, you can use the "break" statement with an optional integer parameter to end a nested loop. The number of enclosing loop structures to break out of is specified by the numeric argument. 


For instance, break would be used to exit a single loop, whereas break 2 would be used to exit two nested loops.


Here's an illustration of how to exit a single loop:


In this case, the loop stops when $i equals 5 because of the break statement. The loop's remaining iterations will be skipped.


<?php

for ($i = 0; $i < 10; $i++) 
{
	for ($j = 0; $j < 10; $j++) 
	{
		if ($j == 5) 
		{
			break 2;
		}
       
		echo $j . "<br />";
	}
}

?>

Output:


0
1
2
3
4

Here is an example of how to break out of two nested loops:


In this case, the loop will end when $j equals 5 through to the break 2 control. Both the remaining inner loop iterations and the remaining outer loop iterations are going to be skipped.


<?php

for ($i = 0; $i < 10; $i++) 
{
	for ($j = 0; $j < 10; $j++) 
	{
		if ($j == 5) 
		{
            break 2;
		}
       
		echo $j. "<br />";
	}
}

?>

Output:


0
1
2
3
4

How to continue the nested loop in PHP

The continue statement in PHP can be employed to continue on a nested loop. The continue statement will start the next iteration of the loop right away, skipping the remainder of the current iteration. 


Following the continue instruction, if you provide a numerical parameter, the program will skip the designated number of enclosing loops. 


Continue 2 will, for instance, skip both the current loop and the next enclosing loop.


In this example, if $j equals 3, the continue expression will skip the remainder of the inner loop. This indicates that the following output will be printed by the loop:


<?php

for ($i = 0; $i < 5; $i++) 
{
	for ($j = 0; $j < 5; $j++) 
	{
		if ($j == 3) 
		{
            continue;
		}
       
		echo $i . ',' . $j . "<br />";
	}
}

?>

Output:


You may observe that when $j equals 3, the loop prints nothing.


0,0
0,1
0,2
0,4
1,0
1,1
1,2
1,4
2,0
2,1
2,2
2,4
3,0
3,1
3,2
3,4
4,0
4,1
4,2
4,4

Second Example,


The continue statement can also be used to jump to an outer loop's next iteration. 


For instance, the code that follows will go on to the next iteration of the outer loop and ignore the present one:


In this case, if $i == 3, the continue command will skip the current outer loop iteration. This indicates that when $i equals 3, the loop won't output any values.


<?php

for ($i = 0; $i < 5; $i++) 
{
	if ($i == 3) 
	{
		continue;
	}

	for ($j = 0; $j < 5; $j++) 
	{
		echo $i . ',' . $j . "<br />";
	}
}

?>

Output:


0,0
0,1
0,2
0,3
0,4
1,0
1,1
1,2
1,3
1,4
2,0
2,1
2,2
2,3
2,4
4,0
4,1
4,2
4,3
4,4

Conclusion:

In conclusion, PHP's break and continue statements are useful tools for managing the way foreach loops run. You can improve your code's flexibility and efficiency by utilizing them properly.

No comments:

Post a Comment

Post Bottom Ad