How to reference the first loop from the second in a looping of loops?

3

In PHP, how can I reference the first for from the second, as in the example below?

for ($i=0; $i < 10; $i++) { 

    for ($j=0; $j < 10; $j++) { 

        // Quero que esse afete o primeiro 'for' e não o segundo
        if ($j == $i) continue;

        echo $j;
    }
}

I learned how to do this using the Kotlin , but is there any way to do something similar in PHP?

    
asked by anonymous 09.08.2017 / 19:01

3 answers

1

You can use a number in continue to identify which loop you want to stop / continue.

This works for break and switch too. And it is counted from the inside out, for example: the innermost loop is the 1.

Example:

See working on repl.it.

for ($i=0; $i < 3; $i++) { 
    echo 'externo' . PHP_EOL;

    for ($j=0; $j < 3; $j++) { 

        // Quero que esse afete o primeiro 'for' e não o segundo
        if ($j == $i) continue 2;

        echo "$i - $j" . PHP_EOL;
    }
}
    
09.08.2017 / 19:05
2

Yes, you can use continue 2; , you can see this in documentation on control structures .

  

The continue accepts an optional numeric argument that tells you how many levels of nested loops to skip. The default value is 1, jumping to the end of the current loop.

This feature also works for break and switch , and counts from the inside out, ie: the inner loop is 1 .

for ($i=0; $i < 10; $i++) { 
    for ($j=0; $j < 10; $j++) { 

        if ($j == $i) continue 2;
        echo $j;
    }
}
// dá: 001012012301234012345012345601234567012345678

Ideone: link

    
09.08.2017 / 19:05
1

Try to use like this, It should work

 if ($j == $i) continue 2;

In the PHP manual:

  

Continue accepts an optional numeric argument that tells how many   levels of nested loops should skip. The default value is 1, jumping   to the end of the current loop ... Documentation

The same thing applies to the break .

  

break accepts an optional numeric argument that tells how many structures   should stop. The default value is 1, only the structure   immediate interruption.

    
09.08.2017 / 19:08