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

5
When I want to break a loop of a for , while or foreach I always use 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 continue:

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

In the manual, you have:

  

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

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

Is it possible to use continue for some purposes or break to break the foreach loop by using switch ?

    
asked by anonymous 20.04.2015 / 23:20

1 answer

7

Yes, it is possible.

According to the documentation on break :

  

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

Documentation about continue :

  

continue accepts an optional numeric argument that tells how many levels   loops nested it should jump to the end. The default value is 1, going   so to 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

    
20.04.2015 / 23:35