break

(PHP 4, PHP 5, PHP 7, PHP 8)

breakは、現在実行中の for, foreach, while, do-while, switch 構造の実行を終了します。

break では、オプションの引数で ネストしたループ構造を抜ける数を指定することができます。 この引数のデフォルトは 1 で、直近のループ構造からだけ抜けます。

<?php
$arr 
= array('one''two''three''four''stop''five');
foreach (
$arr as $val) {
    if (
$val == 'stop') {
        break;    
/* ここでは、'break 1;'と書くこともできます */
    
}
    echo 
"$val<br />\n";
}

/* オプション引数を使用します */

$i 0;
while (++
$i) {
    switch (
$i) {
        case 
5:
            echo 
"At 5<br />\n";
            break 
1;  /* switch 構造のみを抜けます */
        
case 10:
            echo 
"At 10; quitting<br />\n";
            break 
2;  /* switch と while を抜けます */
        
default:
            break;
    }
}
?>

add a note add a note

User Contributed Notes 2 notes

up
4
ei dot dwaps at gmail dot com
3 years ago
You can also use break with parentheses: break(1);

Note:
Using more nesting level leads to fatal error:

<?php
while (true) {
    foreach ([
1, 2, 3] as $value) {
      echo
'ok<br>';
      break
3; // Fatal error: Cannot 'break' 3 levels
   
}
    echo
'jamais exécuter';
    break;
  }
?>
up
-4
mparsa1372 at gmail dot com
3 years ago
The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

<?php
for ($x = 0; $x < 10; $x++) {
  if (
$x == 4) {
    break;
  }
  echo
"The number is: $x <br>";
}
?>
To Top