daGrevis
daGrevis

Reputation: 21333

How to stop foreach cycle without stopping the rest of the PHP script?

Having a foreach loop, is it possible to stop it if a certain condition becomes valid?

Example:

<?php
foreach ($foo as $bar) {

  if (2+2 === 4) {
    // Do something and stop the cycle
  }

}
?>

I tried to use return and exit, but it didn't work as expected, because I want to continue executing the remaining of the PHP script.

Upvotes: 12

Views: 27779

Answers (2)

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124768

Use break:

foreach($foo as $bar) {    
    if(2 + 2 === 4) {
        break;    
    }    
}

Break will jump out of the foreach loop and continue execution normally. If you want to skip just one iteration, you can use continue.

Upvotes: 46

tomsseisums
tomsseisums

Reputation: 13357

http://php.net/manual/en/control-structures.break.php is the answer!

As simple as break;.

Upvotes: 5

Related Questions