PHP/Statement/break statement

Материал из Web эксперт
Перейти к: навигация, поиск

Break 1 or break 2

   <source lang="html4strict">

<? $arr = array( "one", "two", "three", "four", "stop", "five" ); while ( list( , $val ) = each( $arr ) ) {

   if ( $val == "stop" ) {
       break; /* You could also write "break 1;" here. */
   }
   echo "$val
\n";

} $i = 0; while ( ++$i ) {

   switch ( $i ) {
       case 5:
           echo "At 5
\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting
\n"; break 2; /* Exit the switch and the while. */ default: break; }

} ?>

 </source>
   
  


Breaking a Loop

   <source lang="html4strict">

<?php

 for ($a = 1; $a <= 20; $a++){
     $divide = 40/$a;
     echo "The result of dividing 40 by $a is $divide", "
"; }

?>

      </source>
   
  


Break Statement

   <source lang="html4strict">

<html>

<head>
 <title>Break Statement</title>
</head>
<body>
<?php
 $i = 0;
 while ( $i < 6 )
 {
   if( $i == 3) break;
   $i++;
 }
 echo("Loop stopped at $i by break statement");
?>
</body>

</html>

 </source>
   
  


break within a for loop

   <source lang="html4strict">

<?php

  $primes = array(2,3,5,7,11,13);
  for($count = 1; $count++; $count < 1000) {
     $randomNumber = rand(1,50);
     if (in_array($randomNumber,$primes)) {
        break;
     } else {
echo "

Non-prime number encountered: $randomNumber

";
     }
  }

?>

 </source>
   
  


The break command applies to both loops and switch/case statements

   <source lang="html4strict">

for ($i = 1; $i < 3; $i = $i + 1) {

           for ($j = 1; $j < 3; $j = $j + 1) {
                   for ($k = 1; $k < 3; $k = $k + 1) {
                           switch($k) {
                                   case 1:
                                           print "I: $i, J: $j, K: $k\n";
                                           break 2;
                                   case 2:
                                           print "I: $i, J: $j, K: $k\n";
                                           break 3;
                           }
                   }
           }
   }
 
 </source>
   
  


Using break to avoid division by zero

   <source lang="html4strict">

<?php $counter = -3; for (; $counter < 10; $counter++){

   if ($counter == 0){
       echo "Stopping to avoid division by zero.";
       break;
   }
   echo "100/$counter
";

} ?>

 </source>
   
  


Using the break Statement

   <source lang="html4strict">

<html> <head><title>Using the break Statement</title></head> <body>

<?php

   $counter = -4;
   for ( ; $counter <= 10; $counter++ ) {
     if ( $counter == 0 ) {
       break;
     }
     $temp = 4000/$counter;
     print "4000 divided by $counter is.. $temp
"; }

?>

</body> </html>

 </source>