31

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!

headacheCoder
  • 4,503
  • 8
  • 30
  • 33

3 Answers3

23

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;
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
15

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.
}
Ronnie Oosting
  • 1,252
  • 2
  • 14
  • 35
  • `return` works . Simple example : `$items = ['a' , 'b' , 'c']; foreach($items as $item) { echo $item; if($item == 'a') return true; }` – EGurelli Jan 23 '18 at 14:11
  • 1
    Thanks @EGurelli. I've added and edited your example. – Ronnie Oosting Jan 24 '18 at 08:26
  • The second snippet is misleading/bad -- it will never perform more than one iteration. In other words there is no reason to use a `foreach()` in the second snippet -- it could merely be `return $items[0] == 'a';`. – mickmackusa May 27 '22 at 00:40
13

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

Rijk
  • 11,032
  • 3
  • 30
  • 45