PHP continue inside function

Clarissa B picture Clarissa B · May 31, 2011 · Viewed 8.1k times · Source

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?

Answer

Wytse picture Wytse · May 31, 2011

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>';    
}