How to use break Keyword In PHP
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
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
Contact Us