9

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?

Clarissa B
  • 239
  • 2
  • 5
  • 14

4 Answers4

13

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>';    
}
Wytse
  • 500
  • 2
  • 10
7

The continue statement is valid inside looping structures only.

Salman A
  • 262,204
  • 82
  • 430
  • 521
1

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.

alex
  • 479,566
  • 201
  • 878
  • 984
0

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.

John Hargrove
  • 701
  • 6
  • 23