Open In App

How to Break Foreach Loop in PHP?

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 break foreach loop in PHP.

Below are the approaches to break foreach 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
$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
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
    echo $number . "<br>";
    if ($number === 3) {
        goto endloop;
    }
}
endloop:
?>

Output:

1
2
3
Article Tags :