PHP - Break after return?

headacheCoder picture headacheCoder · Sep 2, 2011 · Viewed 26.9k times · Source

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!

Answer

Pekka picture Pekka · Sep 2, 2011

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;