Search code examples
phpfor-loopreturnbreak

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 false;
    // break;
}

Thank you!


Solution

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