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.
1) PHP code to demonstrate example of break in a foreach loop
Output
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?
2) PHP code to use break in a foreach loop with an associative array
Output
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.
need an explanation for this answer? contact us directly to get an explanation for this answer