How to Stop a Foreach Loop in PHP
To stop a foreach loop in PHP, you should use the
break operator.
In the following example, we iterate through an array using a foreach loop and,
as soon as we encounter the number 3,
exit the loop:
<?php
$arr = [1, 2, 3, 4, 5];
foreach ($arr as $elem) {
echo $elem;
if ($elem == 3) {
break; // exit the loop
}
}
?>
Code execution result:
123