Re: Break or continue an outer loop from an inner loop?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, Dec 5, 2017 at 11:33 AM, Jeffry Killen <jekillen@xxxxxxxxxxx> wrote:

> The code  starts a loop and inside the loop for each iteration
> there is an inner loop.
>
> What I need to do is: depending on a conditional, I want to
> tell the outer loop to continue from the inner loop: I.E.
> stop the inner loop iteration and have the outer loop jump
> to its next iteration.


>From the docs for continue [1]:

    continue accepts an optional numeric argument which tells it how many
levels of enclosing loops
    it should skip to the end of. The default value is 1, thus skipping to
the end of the current loop.

    $i = 0;
    while ($i++ < 5) {
        echo "Outer<br />\n";
        while (1) {
            echo "Middle<br />\n";
            while (1) {
                echo "Inner<br />\n";
                continue 3;                // <-- exit outermost while loop
            }
            echo "This never gets output.<br />\n";
        }
        echo "Neither does this.<br />\n";
    }

The same applies to break, even in a switch statement.

On Tue, Dec 5, 2017 at 11:45 AM, Ashley Sheridan <ash@xxxxxxxxxxxxxxxxxxxx>
 wrote:

> If you just want to stop the inner loop and continue the outer one, a
> simple break will do:
>
> for($i=0; $i<10; $i++)
> {
>     for($j=0; $j<10; $j++)
>     {
>         echo "$i, $j\n";
>
>         if($j==6)
>             break;
>     }
> }


This example works, but it will break if the outer loop has more lines of
code following the inner loop.

Cheers!
David

[1] http://php.net/manual/en/control-structures.continue.php

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux