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 indique combien de structures emboîtées doivent être interrompues. La valeur par défaut est 1, seulement la structure emboîtée immédiate est interrompue.

<?php
$arr = array('un', 'deux', 'trois', 'quatre', 'stop', 'cinq');
foreach ($arr as $val) {
    if ($val == 'stop') {
        break;    /* Il est aussi possible d'écrire 'break 1;' ici. */
    }
    echo "$val\n";
}

L'exemple ci-dessus va afficher :

un
deux
trois
quatre

Utilisation de l'argument optionnel :

<?php
$i = 0;
while (++$i) {
    switch ($i) {
        case 5:
            echo "À 5\n";
            break 1;  /* Termine uniquement le switch. */
        case 10:
            echo "À 10 ; arrêt\n";
            break 2;  /* Termine le switch et la boucle while. */
        default:
            break;
    }
    echo "$i\n";
}

L'exemple ci-dessus va afficher :

1
2
3
4
À 5
5
6
7
8
9
À 10 ; arrêt

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top