Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

foreach

php

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.

like image 675
daGrevis Avatar asked Mar 07 '11 11:03

daGrevis


2 Answers

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.

like image 99
Tatu Ulmanen Avatar answered Nov 12 '22 18:11

Tatu Ulmanen


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

As simple as break;.

like image 29
tomsseisums Avatar answered Nov 12 '22 16:11

tomsseisums