PHP/Statement/break statement

Материал из Web эксперт
Версия от 07:07, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Break 1 or break 2

 
<?
$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<br>\n";
}
$i = 0;
while ( ++$i ) {
    switch ( $i ) {
        case 5:
            echo "At 5<br>\n";
            break 1; /* Exit only the switch. */
        case 10:
            echo "At 10; quitting<br>\n";
            break 2; /* Exit the switch and the while. */
            default:
        break;
    }
}
?>



Breaking a Loop

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



Break Statement

 
<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>



break within a for loop

 
<?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 "<p>Non-prime number encountered: $randomNumber</p>";
      }
   }
?>



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

 
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;
                            }
                    }
            }
    }



Using break to avoid division by zero

 
<?php
$counter = -3;
for (; $counter < 10; $counter++){
    if ($counter == 0){
        echo "Stopping to avoid division by zero.";
        break;
    }
    echo "100/$counter<br />";
}
?>



Using the break Statement

 
<html>
<head><title>Using the break Statement</title></head>
<body>
<div>
<?php
    $counter = -4;
    for ( ; $counter <= 10; $counter++ ) {
      if ( $counter == 0 ) {
        break;
      }
      $temp = 4000/$counter;
      print "4000 divided by $counter is.. $temp<br />";
    }
?>
</div>
</body>
</html>