user2525317
user2525317

Reputation: 185

Is there any possibility to break a loop while calling a function?

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?

Upvotes: 0

Views: 99

Answers (3)

Kingalione
Kingalione

Reputation: 4265

Use:

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

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

Upvotes: 1

Simon Brahan
Simon Brahan

Reputation: 2076

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

Upvotes: 1

nickb
nickb

Reputation: 59709

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

Upvotes: 3

Related Questions