PHP 8.4.24 Released!

break

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

La instrucción break permite salir de una estructura for, foreach, while, do-while o switch.

break acepta un argumento numérico opcional que indicará cuántas estructuras anidadas deben ser interrumpidas. El valor por omisión es 1, solo la estructura anidada inmediata es interrumpida.

<?php
$arr = array('un', 'dos', 'tres', 'cuatro', 'stop', 'cinco');
foreach ($arr as $val) {
    if ($val == 'stop') {
        break;    /* También podría utilizarse 'break 1;' aquí. */
    }
    echo "$val\n";
}

El ejemplo anterior mostrará:

un
dos
tres
cuatro

Uso del argumento opcional:

<?php
$i = 0;
while (++$i) {
    switch ($i) {
        case 5:
            echo "At 5\n";
            break 1;  /* Termina únicamente el switch. */
        case 10:
            echo "At 10; quitting\n";
            break 2;  /* Termina el switch y el ciclo while. */
        default:
            break;
    }
    echo "$i\n";
}

El ejemplo anterior mostrará:

1
2
3
4
At 5
5
6
7
8
9
At 10; quitting

add a note

User Contributed Notes

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