How to Break Out of PHP Foreach Loop (With Example)

In PHP, to exit a foreach loop, you can use the break statement. When a certain condition is met, using the break statement will immediately stop the current loop. Here is an example:

$fruits = array("apple", "banana", "orange", "grape");

foreach ($fruits as $fruit) {
  if ($fruit == "orange") {
    break;
  }
  echo $fruit . "<br>";
}

The above code will output:

apple
banana

When the loop reaches the value of the $fruit variable being “orange”, the break statement will end the loop, so only “apple” and “banana” are output.

bannerAds