The PHP foreach Loop Break
To exit a PHP foreach loop,
the break statement is used.
Let's see how it works with the following example: let's say we have an array with numbers, and we want to output its elements until the first encountered three. In this case, we will break the loop.
Implementation:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
echo $elem;
if ($elem == 3) {
break; // exit the loop
}
}
?>
Code execution result:
123