break

(PHP 4, PHP 5, PHP 7)

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

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

<?php
$arr 
= array('one''two''three''four''stop''five');
while (list(, 
$val) = each($arr)) {
    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;
    }
}
?>

break の変更履歴
バージョン 説明
5.4.0 break 0; が使えなくなりました。今までのバージョンでは、これは break 1; と同じ意味に解釈されていました。
5.4.0 数値引数の部分に変数を渡すこと (例: $num = 2; break $num;) ができなくなりました。

add a note add a note

User Contributed Notes 5 notes

up
129
steve at electricpocket dot com
5 years ago
A break statement that is in the outer part of a program (e.g. not in a control loop) will end the script. This caught me out when I mistakenly had a break in an if statement

i.e.

<?php
echo "hello";
if (
true) break;
echo
" world";
?>

will only show "hello"
up
13
traxer at gmx dot net
11 years ago
vlad at vlad dot neosurge dot net wrote on 04-Jan-2003 04:21

> Just an insignificant side not: Like in C/C++, it's not
> necessary to break out of the default part of a switch
> statement in PHP.

It's not necessary to break out of any case of a switch  statement in PHP, but if you want only one case to be executed, you have do break out of it (even out of the default case).

Consider this:

<?php
$a
= 'Apple';
switch (
$a) {
    default:
        echo
'$a is not an orange<br>';
    case
'Orange':
        echo
'$a is an orange';
}
?>

This prints (in PHP 5.0.4 on MS-Windows):
$a is not an orange
$a is an orange

Note that the PHP documentation does not state the default part must be the last case statement.
up
0
Anonymous
3 months ago
If you are wondering, break and break() are equivalent:

<?php

 
break(2);

  break
2;   //same result

?>
up
1
RK
6 years ago
If the numerical argument is higher than the number of things which can be broken out of, it seems to me like the execution of the entire program is stopped.
My program had 8 nested loops. Didn't bother counting them, but wrote: break 10. - Result: Code following the loops was not processed.
up
-4
Anonymous
10 years ago
If you wonder how to end execution of a function (as I did), it's that simple: return

function foo($a) {
if(!$a) return;
echo 'true';
// some other code
}

foo(true) will echo 'true', foo(false) won't echo anything (as return ends execution of the function. Of course, therefore there is no need for 'else' before 'echo').
To Top