59 of 110 menu

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