109 of 110 menu

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

English
БеларускаяEspañolРусский
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline