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!


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; 

if (some_condition)

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


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.


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

Need Your Help

Building with xcodebuild Timed out waiting for <IDEWorkspace, 0x2004cebc0>/"runContextManager.runContexts"

iphone osx-snow-leopard xcodebuild

I am setting up my iphone project to run with hudson, my build script works fine locally, but when executing the following command on my snow leopard server mac

How to use ASP.NET Session State in an HttpHandler?

httphandler session-state

I have an HttpHandler that is run on a client page (cross domain, not on our IIS server, etc) and when they click on our embedded link it fires off the Handler on our server. So far everything is