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!
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.
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.
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.
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.
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;
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. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With