0

Let's say I have a simple code:

while(1) {
  myend();
}

function myend() {
  echo rand(0,10);
  echo "<br>";
  if(rand(0,10) < 3) break;
}

This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.

So is there any possibility to terminate the loop during a subfunctin execution?

2
  • 2
    No, you must instead return a value from the function and break based on its value Commented Sep 15, 2014 at 12:58
  • stackoverflow.com/questions/6183713/… Commented Sep 15, 2014 at 12:59

3 Answers 3

3

Make the loop condition depend upon the return value of the function:

$continue = true;
while( $continue) {
    $continue = myend();
}

Then, change your function to be something like:

function myend() {
  echo rand(0,10);
  echo "<br>";
  return (rand(0,10) < 3) ? false : true;
}
Sign up to request clarification or add additional context in comments.

2 Comments

rather, do {... } while(fun()).
myend in my case will be evaluated too.
1

There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:

while(1) {
  if (myend())
    break;
}

function myend() {
  echo rand(0,10);
  echo "<br>";
  return rand(0,10) < 3;
}

Comments

1

Use:

$cond = true;
while($cond) {
  $cond = myend();
}

function myend() {
  echo rand(0,10);
  echo "<br>";
  if(rand(0,10) < 3) return false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.