(PHP 4, PHP 5, PHP 7, PHP 8)
L'instruction break
permet de sortir d'une structure for
, foreach
, while
, do-while
ou switch
.
break
accepte un argument numérique optionnel qui vous indiquera combien de structures emboîtées doivent être interrompues. La valeur par défaut est 1
, seulement la structure emboitée immédiate est interrompue.
<?php
$arr = array('un', 'deux', 'trois', 'quatre', 'stop', 'cinq');
foreach ($arr as $val) {
if ($val == 'stop') {
break;
}
echo "$val<br />\n";
}
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1;
case 10:
echo "At 10; quitting<br />\n";
break 2;
default:
break;
}
}
?>