PHP - Break after return?

30,963

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

Solution 2

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

Solution 3

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

Share:
30,963
headacheCoder
Author by

headacheCoder

Updated on October 22, 2021

Comments

  • headacheCoder
    headacheCoder over 2 years

    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!