-->

PHP continue inside function

2020-06-12 06:21发布

问题:

This is likely very trivial but I haven't been able to figure it out.

This works:

function MyFunction(){

//Do stuff

}


foreach($x as $y){

MyFunction();

if($foo === 'bar'){continue;}

//Do stuff

echo $output . '<br>';

}

But this doesn't:

function MyFunction(){

//Do stuff

if($foo === 'bar'){continue;}

}


foreach($x as $y){

MyFunction();

//Do stuff

echo $output . '<br>';

}

That yields only 1 $output and then:

Fatal error: Cannot break/continue 1 level

Any idea what I'm doing wrong?

回答1:

You can't break/continue a loop outside a function, from within a function. However, you can break/continue your loop based on the return value of your function:

function myFunction(){   
    //Do stuff
    return $foo === 'bar';
}


foreach($x as $y) {
    if(myFunction()) {
        continue;
    }

    //Do stuff

    echo $output . '<br>';    
}


回答2:

The continue statement is valid inside looping structures only.



回答3:

continue can only skip iterations inside of a looping structure.

Inside of your function, the context of it being ran inside a loop is lost.



回答4:

The function is compiled separately and could be called from anywhere. Thus, the use of continue makes no sense here as the context is not in that of a loop. If you wish to delegate work to a function here, you should design the function to return some indication of whether to continue or not, such as a TRUE or FALSE return value.