Using BREAK within a while

Asked

Viewed 435 times

4

Hi.

I have a php function that returns N values from the database. For each returned data I must do an validity check, and if one of them does not pass the validation, it is unnecessary to validate the others.

It is a good programming practice to put a break inside the loop so that the program does not validate the other records?

2 answers

4

Yes it’s good practice.

Make it clear where this line of code is so it’s not hard to debug if you have a problem and don’t see that the line is there.

Whenever there are unnecessary iterations, breaking the loop is good, not only in PHP.

  • i had shielded the reverse. so of the question. until it is something related to multiples Return within the same function.

  • @Gustavoemmel, if you have an example you can ask the question. If it is to prevent too many iterations, the break is worth it. Multiples Returns can be a case of code that needs to be rebuilt.

  • Well, actually, it’s like you guys are saying my code, and the idea I had was just to avoid those iterations. but perhaps it is a better practice to delimit in sql query.

  • 1

    @Related Gustavoemmel: http://answall.com/questions/20660/por-que-o-uso-goto- %C3%A9-considered-bad/20874#20874. People talk a lot without understanding the context. Break is a more controlled drop. It’s bad when it turns messy, but to simplify code and demonstrate intent, it’s great.

  • I think that not only is it good practice, as together and opposite with/to continue, are the only options to get out of a loop without leaning on an external counter. I do not know if the goto of PHP serves for this too.

3

Yes, it is good practice to avoid unnecessary iterations, an option if you do not want to use break for legibility reasons, would use an auxiliary variable to test the loop, example:

$valido = true;
$n = 0;
//Enquanto menor 10 e válido
while ($n < 10 && $valido){
  echo $n; 
  echo PHP_EOL;
  if($n == 5) { // sua validação
    $valido = false;
  }
  $n++;
}

Example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.