简体   繁体   中英

Can i end While loop with function?

I tried to google this and i think it can't be done but i have to ask anyway. If i have while loop?

while ($smth > 1)
{
  func();
}

Is there a way i could exit the while loop immediately with that function inside it? Maybe that function returns something that stop loop? I tried

func(){ 
return break;}

but this doesn't work.

It's not possible the way you've done it -- you can't return a break. But you can return a value that could signal to exit the loop.

function func() {
  return true
}

And then

while($smth > 1) {
  if(func()) break;
}

This will run the function, but it will also check it's return value to verify it does not need to exit the loop. If the function returned true, the if statement is satisfied and so a break will occur. If the function doesn't return explicitly, the if will not be satisfied.

You sort of can get out of that while loop from inside that function by throwing an exception. Your teammates will not like you anymore, however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM