skip current iteration

PhpLoops

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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
}

Solution 2 - Php

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

Solution 3 - Php

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

Solution 4 - Php

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

dinel

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHailwoodView Question on Stackoverflow
Solution 1 - PhpMatthew ScharleyView Answer on Stackoverflow
Solution 2 - PhpBrad ChristieView Answer on Stackoverflow
Solution 3 - PhpJayminLimbachiyaView Answer on Stackoverflow
Solution 4 - PhpdinelView Answer on Stackoverflow