Open In App

How to Break Foreach Loop in PHP?

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Using break Keyword

In 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.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
    echo $number . "<br>";
    if ($number === 3) {
        break; 
    }
}
?>

Output:

1
2
3

Using goto Keyword

In 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.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
    echo $number . "<br>";
    if ($number === 3) {
        goto endloop;
    }
}
endloop:
?>

Output:

1
2
3

Using array_filter FunctionAdded

In 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.

PHP
<?php
// Nikunj Sonigara
$numbers = [1, 2, 3, 4, 5];
$filteredNumbers = array_filter($numbers, function($number) {
    return $number <= 3;
});

foreach ($filteredNumbers as $number) {
    echo $number . "\n";
}
?>

Output
1
2
3

Using array_walk with Exception Handling

Another 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.

PHP
<?php
function breakLoop($number) {
    if ($number === 3) {
        throw new Exception("Breaking the loop");
    }
    echo $number . "\n";
}

$numbers = [1, 2, 3, 4, 5];

try {
    array_walk($numbers, 'breakLoop');
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

Output
1
2
Breaking the loop

Next Article

Similar Reads