![]() |
Breaking a foreach loop consists of terminating the execution of the loop prematurely based on a certain condition. In this article, we will explore and learn two approaches to breaking for each loop in PHP. Below are the approaches to break for each loop in PHP: Table of Content Using break KeywordIn this approach, we are using the break keyword within a foreach loop in PHP to prematurely exit the loop when the condition $number === 3 is met. This makes sure that only the elements before the number 3 in the $numbers array are processed and printed. Syntax: break; Example: The below example uses the break keyword to break foreach loop in PHP.
Output: 1
2
3 Using goto KeywordIn this approach, we are using the goto keyword within a foreach loop in PHP to jump to a labeled section called endloop when the condition $number === 3 is met. This breaks the loop and continues execution after the labeled section. Syntax: goto labelName; Example: The below example uses the goto keyword to break foreach loop in PHP.
Output: 1
2
3 Using array_filter FunctionAddedIn this approach, we use the array_filter function to filter the array elements before the foreach loop starts. By only including elements before the specified condition in the array, we can effectively break the loop indirectly. Syntax: array_filter(array $array, callable $callback) Example: The below example uses the array_filter function to filter elements up to the number 3, thus breaking the foreach loop indirectly.
Output 1 2 3 Using array_walk with Exception HandlingAnother approach to breaking a foreach loop in PHP is by using array_walk in combination with exception handling. This method involves throwing an exception when a certain condition is met within the array_walk callback, which effectively stops the iteration. Example: In this example we will see how to use array_walk and exception handling to break a foreach loop in PHP.
Output 1 2 Breaking the loop |
Reffered: https://www.geeksforgeeks.org
PHP |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |