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

Asked

Viewed 94 times

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 to do it using language Kotlin, but there is some way to do something similar in PHP?

3 answers

2

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

continue accepts an optional numerical argument that tells you how many nested loop levels to skip. Default value is 1, bouncing to the end of the current loop.

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

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

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

Ideone: https://ideone.com/ga4Vzo

  • 2

    wow.... hahaha!!!

1


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

This works to break and switch also. And it is counted from the inside out, for example: the innermost loop is 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;
    }
}
  • A question: it works the same way for the break?

  • @Wallacemaxters Yes, fit to edit =D

1

Try it like this, it should work

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

In the PHP manual:

continue accepts an optional numeric argument that says how many nested loop levels must jump. The default value is 1, bouncing to the end of the current loop... Documentation

The same thing applies to break.

break accepts an optional numeric argument that tells how many structures nested must stop. Default value is 1, only structure immediate is interrupted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.