How to Stop a Loop in PHP
To stop a loop
in PHP, you should use the
break statement.
In the following example, we iterate through an array
using a foreach loop and, as soon as
we encounter the number 3, we 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
The break statement also works in
for and while loops. Use it
by analogy with the previous example.
See Also
-
lesson
The foreach Loop in PHP -
lesson
The while Loop in PHP -
lesson
The for Loop in PHP