Php, include file that uses the continue statement

I came across this situation ((extracted from php docs))

Using the continue statement in a file included in the loop will result in an error. For instance:

// main.php for($x=0;$x<10;$x++) { include('recycled.php'); } // recycled.php if($x==5) continue; else print $x; 

it should print "012346789" not five, but causes an error:

 Cannot break/continue 1 level in etc. 

there is a solution for this, I mean, I need to "process" recycled.php in such a way when using the continue operator does not cause this error, remember that this is a simple clear code example, in the real case I need to find a way to continue the loop file main.php. .

+4
source share
7 answers

You can use return instead of continue inside page2.php :

 if ($x == 5) { return; } print $x; 

If the current script file has been included or is required, then control is transferred back to the calling file. In addition, if the current script file was included, then the value returned by the return will be returned as the value of the incoming call.

PHP: return

+6
source

Simple does NOT include a page for X = 5 ?!

 for($x=0;$x<10;$x++) { if ($x != 5) include('page2.php'); } 

you cannot continue because page2.php is launched inside the scope of the include () function, which does not know the outer loop.

You can use return instead of continue inside page2.php (this will β€œreturn” the include function):

 if ($x == 5) return; echo $x; 
+2
source

As an alternative to using continue, which will not work in such files, you can do this instead:

 // page2.php if($x!=5) { // I want this to run print $x; } else { // Skip all this (ie probably the rest of page2.php) } 
+1
source

Try it! This might work for you.

 // page1.php for($x=0;$x<10;$x++) { include('page2.php'); // page2.php if($x==5) continue; else print $x; } 
0
source

You can also do it

 // page1.php for($x=0;$x<10;$x++) { include('page2.php'); } // page2.php if($x==5) { } // do nothing and the loop will continue else print $x; 
0
source

you want to continue the loop on the page:

try the following:

  for($x=0;$x<10;$x++) { $flag = 1; if($flag==0){ continue; } include('./page2.php'); } if($x==4) $flag = 0; else print $x; 
0
source

Your code is incorrect because you are using a continuation not in a loop! I do not know why you want to include the same file 5 times.

 for($x=0;$x<10;++$x) { //include('page2.php'); if($x!=5) print $x; } 
0
source

Source: https://habr.com/ru/post/1484990/


All Articles