Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP continue inside function

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?

like image 657
Clarissa B Avatar asked May 31 '11 06:05

Clarissa B


People also ask

Can I use continue in foreach PHP?

Introduction. The continue statement is one of the looping control keywords in PHP. When program flow comes across continue inside a loop, rest of the statements in current iteration of loop are skipped and next iteration of loop starts. It can appear inside while, do while, for as well as foreach loop.

Why we use continue in PHP?

The PHP continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. The continue statement is used within looping and switch control structure when you immediately jump to the next iteration.

How do I stop a while loop in PHP?

To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.

What is use of break and continue statements in PHP scripts?

The break statement terminates the whole iteration of a loop whereas continue skips the current iteration. The break statement terminates the whole loop early whereas the continue brings the next iteration early.


2 Answers

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>';    
}
like image 94
Wytse Avatar answered Nov 04 '22 03:11

Wytse


The continue statement is valid inside looping structures only.

like image 39
Salman A Avatar answered Nov 04 '22 05:11

Salman A