Is it possible to use the "break" argument on a "switch" to interrupt a loop?

Asked

Viewed 281 times

5

When I want to interrupt a loop of one for, while or foreach always use the break; within a if with the following structure:

$teste = array(1,2,3,4,5);
foreach($teste as $t){
   if($t == 3){
   echo "Terminando loop ao achar o número ".$t;
   break;
   }
   echo $t."<br />";
}
echo "fim de script";

We can use the continue:

 foreach($teste as $t){
       if($t == 3){
       echo "O ".$t." é meu!";
       continue;
       }
       echo $t."<br />";
    }
    echo "fim de script";

In the manual, there’s this:

Note that in PHP the switch is considered a loop structure for purposes of the continue.

But if you want the switch instead of if, and stop the structure foreach when a particular occurrence is found?

it is possible to use the continue for some purposes or the break to interrupt the loop of foreach making use of the switch?

1 answer

7


It is possible yes.

According to documentation on the break:

break accepts an optional numeric argument that tells it how many nested structures it should finish.

Documentation on the continue:

continue accepts an optional numeric argument that says how many levels nested loops it must skip to the end. The default value is 1, going thus towards the end of the current loop.

Example:

$teste = array(1, 2, 3, 4, 5);

foreach($teste as $t){
    switch($t){
        case 1:
          echo "Terminando loop ao achar o número 1<br>";
          break(2); // Finaliza o switch e o for
        case 2:
          echo "Terminando loop ao achar o número 2<br>";
          break;
        case 3:
          echo "Terminando loop ao achar o número 3<br>";
          break;
        default:
          echo "Terminando loop, nenhum número foi achado<br>";
    }
}
echo "fim de script";

DEMO

  • 1

    I didn’t know that 02 within the break that’s what it was for! Thanks.

  • 2

    I didn’t know this either, I just thought parentheses were unnecessary (), but does not invalidate the answer. + 1

Browser other questions tagged

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