Home »
PHP »
PHP Programs
How to break a foreach loop in PHP?
PHP | Using break in a foreach loop: In this article, we are going to learn how to break a foreach loop in PHP programming?
By Kongnyu Carine Last updated : December 6, 2023
Prerequisites
To understand this solution, you should have the knowledge of the following PHP programming topics:
PHP - Breaking a foreach loop
The break is a keyword that is used to stop the execution of a process after a certain number or after meeting up with particular criteria and transfers the control of the program execution to the next statement written just after the loop body.
In this article, we will learn how to break foreach loop? To break a foreach loop means we are going to stop the looping of an array without it necessarily looping to the last elements because we got what is needed at the moment.
Break out of foreach loop: Example 1
Here, we have an array of the names and breaking the loop execution when a specified string found.
PHP code to demonstrate example of break in a foreach loop
<?php
// array defination
$names = array("joe", "liz", "dan", "kelly", "joy", "max");
// foreach loop
foreach ($names as $name) {
// display of the loop
echo $name . "<br>";
// stop when name is equal to dan
if ($name == "dan") {
break;
}
}
?>
The output of the above example is:
joe
liz
dan
Break out of foreach loop: Example 2
Let's see how to use the break foreach using an associative array that contains the names and ages to display names and age of 2 members of the array?
PHP code to use break in a foreach loop with an associative array
<?php
//array definition
$members = array("joe" => "12", "liz" => "13", "sam" => "14", "ben" => "15");
//variables to count
$count = 0;
//number f display or loop
$end = 2;
foreach ($members as $key => $value) {
$count++; // increment the counter
//display
printf("%s is %d years old<br>", $key, $value);
//stop when $count equals $end
if ($count == $end) {
break;
}
}
?>
The output of the above example is:
joe is 12 years old
liz is 13 years old
In this example, we have defined a $count variable to count the number of loops and compare with the $end variable. The $end variable can be any number, it all depends on the number of iterations we need.
PHP Basic Programs »