break

(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;
/* Vous pourriez aussi utiliser 'break 1;' ici. */
}
echo
"$val<br />\n";
}

/* Utilisation de l'argument optionnel. */

$i = 0;
while (++
$i) {
switch (
$i) {
case
5:
echo
"At 5<br />\n";
break
1; /* Termine uniquement le switch. */
case 10:
echo
"At 10; quitting<br />\n";
break
2; /* Termine le switch et la boucle 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