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?
Submitted by Kongnyu Carine, on May 27, 2019 [Last updated : March 12, 2023]
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.
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;
}
?>
Output
joe
liz
dan
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;
}
?>
Output
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 »