Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 216
headacheCoder Avatar asked Sep 02 '11 08:09

headacheCoder


People also ask

Can we put break after return?

No you don't need to use break . It is used to terminate a loop early, but return (within a subroutine) will also terminate any loop it is inside of. Anything that follows return is dead code.

Does return break while loop PHP?

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.

How do you stop a PHP loop?

Using break keyword: The break keyword is used to immediately terminate the loop and the program control resumes at the next statement following the loop. To terminate the control from any loop we need to use break keyword.

Can I use break in PHP?

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only. The break keyword immediately ends the execution of the loop or switch structure.


2 Answers

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; 
like image 115
Pekka Avatar answered Oct 12 '22 22:10

Pekka


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. } 
like image 41
Ronnie Oosting Avatar answered Oct 13 '22 00:10

Ronnie Oosting