Assume you have this code:
function doSomething($array)
{
for($i = 0; $i < sizeof($array); $i++)
{
if ($array[$i] == "ok")
return true;
}
return false;
}
Note that I'm not talking about PHP specific (this applies to all languages) or this particular example. It's about breaking in the for loop (in this case, return true; stops the loop).
According to a teacher of me, this is very, very bad and a not-done practice.
Is breaking from a loop really a not-done practice?
Thanks
It is perfectly fine to break or return from a loop.
What your teacher possibly refers to is the classic a function should have only one return point extended to loops. The rationale behind this is, that your control flow should always be as easy and understandable as possible. It's not a strict rule that you have to obey without thinking.
To rewrite your sample without using break and return:
function doSomething($array)
{
$ret = false;
for($i = 0; $i < sizeof($array) && !$ret; $i++)
{
if ($array[$i] == "ok")
$ret = true;
}
return $ret;
}
That's painful to read and maintain. Yours is mich more concise.
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