Skip Record within a while

Asked

Viewed 1,513 times

5

I wonder how it is that I jump a log inside a while?

For example, when the guy is 2 he jumps

while($pessoa = mysqli_fetch_object($query)){
  if($pessoa->tipo == 2){break;}
//continua a exibição de pessoa
}

However, when executing this it for the execution of all the while, how to solve?

  • 1

    You can do something like if($pessoa->tipo != 2){ //executa todas ações...} when type is 2 no record will be displayed. If you need only one record of type 2 to be skipped add a flag to control this.

  • Check it out:https://answall.com/questions/207170/para-que-serve-o-controle-de-fluxo-continue

5 answers

7

Using the break command will actually break the loop. To continue normally use continue;

That is to say..

while($pessoa = mysqli_fetch_object($query)){
  if($pessoa->tipo == 2)
    continue;
 //  não irá executar os comandos que tiverem após essa condição.
}
  • 1

    if($pessoa->tipo != 2)

  • Or this ... but each has its own option.

  • 1

    In case he wants to skip 2, then it should be different, not equal, if it is equal, he will only continue the action when the value is 2

  • Then test first and then say the result.

5

Only performs the condition if different from 2

 while($pessoa = mysqli_fetch_object($query)){
    if($pessoa->tipo != 2){
     //continua a exibição de pessoa
    }
 }

4

Can you assemble a logic that 'deletes' the type 2 record, asking in comparison the type is different from two? In code it is like this:

while($pessoa = mysqli_fetch_object($query)){
  if($pessoa->tipo != 2){
    //executa todas as ações ... dos demais tipos
  }
}

2

All the answers already satisfy your need, but I also propose a different approach:

while($pessoa = mysqli_fetch_object($query)){
  if( in_array($pessoa->tipo, array(/* 2,...outros valores que devem ser pulados*/) ) ){
    continue;
  }
}

Or else

while($pessoa = mysqli_fetch_object($query)){
  if( ! in_array($pessoa->tipo, array(/* 2,...outros valores que devem ser pulados*/) ) ){
    /* Seu código */
  }
}

So I think it’s a little easier to define in which records (if it’s more than one) it should jump.

https://repl.it/IpE9

2

If you want to ignore the tipo of 2 completely, it would be ideal not to get them from the database, using for example:

$query = "SELECT * FROM tabela WHERE tipo != 2";

If the 2 is maximum type, can use the tipo < 2.

Thus the mysqli_fetch_object will get only the values where the tipo is not 2, no need to handle this in PHP.


Another option, different from the others, is to use the GOTO, there jmp:

while($pessoa = mysqli_fetch_object($query)){

  if($pessoa->tipo === '2'){
     goto fim;
  }

  echo 'Você não é 2!';  // Executa o que tem que fazer.

  fim: // Se ele for `2` ele vem direto para cá. :D
}

Test this.

Browser other questions tagged

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