开发者

PHP - Break after return?

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 f开发者_运维百科alse;
    // break;
}

Thank you!


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;


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

or:

$items = ['a' , 'b' , 'c']; 
    
foreach($items as $item)
{
    return $item == 'a'; // if 'a' is found, true is returned. Otherwise false.
}


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜