break

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

break termina l'esecuzione della struttura di controllo for, foreach, while, do-while o switch corrente.

break accetta un argomento numerico che indica da quanti livelli di strutture annidate si intende "uscire". Il valore predefinito è 1, si uscirà quindi solo dalla struttura immediatamente annidata.

<?php
$arr
= array('one', 'two', 'three', 'four', 'stop', 'five');
foreach (
$arr as $val) {
if (
$val == 'stop') {
break;
/* Equivalente a 'break 1;' */
}
echo
"$val<br />\n";
}

/* Utilizzo dell'argomento facoltativo */

$i = 0;
while (++
$i) {
switch (
$i) {
case
5:
echo
"At 5<br />\n";
break
1; /* Termina solo lo switch. */
case 10:
echo
"At 10; quitting<br />\n";
break
2; /* Termina lo switch ed il while. */
default:
break;
}
}
?>

add a note

User Contributed Notes 1 note

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;
}
?>
To Top