How to use goto Keyword In PHP
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
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:
Table of Content
- Using break Keyword
- Using goto Keyword