2

If, within a for loop, there is an included file, and in that included file, there's another for loop, a continue 2 doesn't work

is this by design? or is this a bug? AM totally at a loss

info below

contents of file temp_outer_loop.php

<pre>
    <?php

    for ($z=0; $z < 20 ; $z++) { 
        echo "\r\nlooping z $z of 20";

        for ($a=0; $a < 20 ; $a++) { 
            echo "\r\n\tlooping a $a of 20";
            if ($a==10) continue 2;
        }

    }

    echo "<hr>";


    for ($x=0; $x < 20 ; $x++) { 
        echo "\r\nlooping x $x of 20";

        include_once(__DIR__ . "/temp_inner_loop.php");
    }




?>

contents of file temp_inner_loop.php

<?php

    for ($y=0; $y < 20 ; $y++) { 
        echo "\r\n\tlooping y $y of 20";

        if ($y==5) continue 2; 

    }

?>
5
  • One thing I'm not sure about is that it makes the temp_inner_loop.php very specific, it can only fit if you include it in a loop. This limits the point of making it an include file IMHO. Commented Nov 16, 2019 at 8:18
  • What is continue 2? Commented Nov 16, 2019 at 8:22
  • 2
    @vivek_23 "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." Commented Nov 16, 2019 at 8:23
  • @FrankerZ Thanks. Good to know. Looks like PHP gives this privilege and isn't present in every language. Commented Nov 16, 2019 at 8:33
  • When I tried, I got a fatal error. So naturally it has a separate execution context. You can remove the continue 2 statement and see how it prints. Commented Nov 16, 2019 at 8:40

1 Answer 1

2

I do not believe this is a bug. See this post back in 2006 on the bug tracker. It states:

"include" in PHP is not "#include" in C. It doesn't just copy&paste your code. The included file has a separate execution context, even though it does inherit some things, most notably the symbol table from the including scope. You will also notice that writing "return" in the included file acts as a return from the file, not from the function it might be included in.

This kind of cross-file goto is definitely not intended to work.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @FrakerZ . I thought an inclusion is as good as a "cross file goto".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.