96 of 110 menu

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
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