This is a tutorial on how to break out of a foreach loop in PHP. This can be useful if you want to exit the loop after a certain number of iterations, or if you want to check whether or not an array has any more items that need iterating through.
With break
in the foreach
loop you will break out of the current loop. Once it is broken, any functions that are called in the loop will not be executed anymore. Also, if you have a condition in your foreach
loop with ‘break‘ or ‘continue‘, then it will skip each iteration to that point.
CONTENTS
How to break and continue foreach loop in php?
“break” is actually a keyword in coding that makes foreach loop stop on its own. This can be especially useful when you want to break out of a loop based on some condition or after getting a specific array index. For example:
<?php
$data = [1,2,3];
foreach($data as $value) {
if ($value > 1){
break;
}
echo $value;
}
?>
Output:
1
Whereas the word “continue” also works this way. If there’s some code following a foreach loop where we want our program not just repeat every time through once more (so instead jump down below), then using “continue” at top saves us from having to restart everything again right away by skipping straight ahead next iteration. For example:
<?php
$data = [1,2,3];
foreach($data as $value) {
if ($value == 2){
continue;
}
echo $value;
}
?>
The output will be 1 and 3. This is because we are checking if the $value is 2, just skip the next statement and move to the next iteration.
Stop a foreach loop with an associative array.
<?php
$fruits = [
"mango" => "2",
"apple" => "4",
"litchi" => "1",
"banana" => "6"
];
$count = 1;
//when exit from loop
$stop = 3;
foreach ($fruits as $key => $value) {
printf("The price of %s is $%d.<br>", $key, $value);
//stop
if ($count == $stop){
break;
}
$count++;
}
?>
Output:
The price of mango is $2.
The price of apple is $4.
The price of litchi is $1.
Conclusion:
In this blog post, we’ve covered how to break a foreach loop in PHP. This is an essential skill for developers and one you will need when working with arrays or collections of data. If you want to learn more about breaking foreach loops, check out the tutorial on our website!