PHP, continue; on foreach(){ foreach(){

PhpForeach

Php Problem Overview


Is there a way to continue on external foreach in case that the internal foreach meet some statement ?

In example

foreach($c as $v)
{
    foreach($v as $j)
    {
        if($j = 1)
        {
            continue; // But not the internal foreach. the external;
        }
    }
}

Php Solutions


Solution 1 - Php

Try this, should work:

continue 2;

From the PHP Manual:

> Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

here in the examples (2nd exactly) described code you need

Solution 2 - Php

Try this: continue 2; According to manual:

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. 

Solution 3 - Php

There are two solutions available for this situation, either use break or continue 2. Note that when using break to break out of the internal loop any code after the inner loop will still be executed.

foreach($c as $v)
{
    foreach($v as $j)
    {
        if($j = 1)
        {
            break;
        }
    }
    echo "This line will be printed";
}

The other solution is to use continue followed with how many levels back to continue from.

foreach($c as $v)
{
    foreach($v as $j)
    {
        if($j = 1)
        {
            continue 2;
        }
    }
    // This code will not be reached.
}

Solution 4 - Php

This will continue to levels above (so the outer foreach)

 continue 2

Solution 5 - Php

<?php
foreach($c as $v)
{
    foreach($v as $j)
    {
        if($j = 1)
        {
            continue 2; // note the number 2
        }
    }
}
?>

RTM

Solution 6 - Php

Try break instead of continue.

You can follow break with an integer, giving the number of loops to break out of.

Solution 7 - Php

you have to use break instead of continue, if I get you right

Here I wrote an explanation on the matter: https://stackoverflow.com/questions/5167561/loop-break-continue-break-2-continue-2-in-php/5167791#5167791

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
QuestionKodeFor.MeView Question on Stackoverflow
Solution 1 - Phpuser973254View Answer on Stackoverflow
Solution 2 - PhpmatinoView Answer on Stackoverflow
Solution 3 - PhpMarcusView Answer on Stackoverflow
Solution 4 - PhpJNDPNTView Answer on Stackoverflow
Solution 5 - PhpdaiscogView Answer on Stackoverflow
Solution 6 - PhpTRiGView Answer on Stackoverflow
Solution 7 - PhpYour Common SenseView Answer on Stackoverflow