PHP - Break after return?

2020-08-09 05:10发布

问题:

do I need to use break here or will it stop looping and just return once?

for($i = 0; $i < 5; $i ++) {
    if($var[$i] === '') return false;
    // break;
}

Thank you!

回答1:

It will run just once, stop looping, and exit from the function/method.

It could be argued though that this is bad style. It is very easy to overlook that return later, which is bad for debugging and maintenance.

Using break might be cleaner:

for($i = 0; $i < 5; $i ++) {
    if($var[$i] === '')
     { set_some_condition; 
       break;
     }
}

if (some_condition)
 return;


回答2:

If you use return, your function (or entire script) will return - all code after that won't be executed. So to answer your question: a break is not required here. However, if the break was not commented out here, the loop would have stopped after one iteration. That's because your if statement doesn't use braces ({ ... }) so it only covers the return statement (in other words: the break in your example is always executed).



回答3:

Update:

PHP 7 requires a return. A break; is not needed because the loop ends on return.

A break; is usually used in a switch or loop whenever you have found your needed item.

Example:

$items = ['a' , 'b' , 'c']; 

foreach($items as $item) 
{ 
   if($item == 'a') 
   {
       return true; // the foreach will stop once 'a' is found and returns true. 
   }

   return false; // if 'a' is not found, the foreach will return false.
}