83

I have a php array $numbers = array(1,2,3,4,5,6,7,8,9)

if I am looping over it using a foreach foreach($numbers as $number)

and have an if statement if($number == 4)

what would the line of code be after that that would skip anything after that line and start the loop at 5? break, return, exit?

Hailwood
  • 89,623
  • 107
  • 270
  • 423

4 Answers4

157

You are looking for the continue statement. Also useful is break which will exit the loop completely. Both statements work with all variations of loop, ie. for, foreach and while.

$numbers = array( 1, 2, 3, 4, 5, 6, 7, 8, 9 );
foreach( $numbers as $number ) {
    if ( $number == 4 ) { continue; }
    // ... snip
}
Howdy_McGee
  • 10,422
  • 29
  • 111
  • 186
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
  • ah continue, Thank's, I had tried all my above mentioned options. Will accept asap – Hailwood Feb 17 '11 at 00:38
  • Isn't `continue` considered a bad coding practice? For the same reasons as `goto`... – Slava Jan 01 '17 at 20:27
  • 4
    Not really. Jumps aren't bad. `goto` as implemented in languages that actually had it let you jump to literally anywhere in the application, that's what was bad. Function calls, conditional statements, anything that introduces branching, they all use jumps and that's ok. `continue` has a single well defined use case. It's fine. If anything `break` is worse. – Matthew Scharley Jan 01 '17 at 21:30
27
continue;

Continue will tell it to skip the current iteration block, but continue on with the rest of the loop. Works in all scenerios (for, while, etc.)

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • 2
    *"skip the current iteration block, but continue on with the rest of the loop"* Thanks, a very clear way to express it. – Alvaro Apr 23 '17 at 15:57
14

Break; will stop the loop and make compiler out side the loop. while continue; will just skip current one and go to next cycle. like:

$i = 0;
while ($i++)
{
    if ($i == 3)
    {
        continue;
    }
    if ($i == 5)
    {
        break;
    }
    echo $i . "\n";
}

Output:

1
2
4
6 <- this won't happen
Community
  • 1
  • 1
JayminLimbachiya
  • 971
  • 1
  • 13
  • 19
2

I suppose you are looking for continue statement. Have a look at http://php.net/manual/en/control-structures.continue.php

dinel

dinel
  • 56
  • 2