Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break in for loop

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

like image 268
Bv202 Avatar asked Mar 05 '26 22:03

Bv202


1 Answers

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.

like image 87
Alexander Gessler Avatar answered Mar 09 '26 11:03

Alexander Gessler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!