break

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

break finaliza a execução da estrutura for, foreach, while, do-while ou switch atual.

break aceita um argumento numérico opcional que diz quantas estruturas aninhadas deverá interromper. O valor padrão é 1, somente a estrutura imediata é interrompida.

<?php
$arr 
= array('one''two''three''four''stop''five');
foreach (
$arr as $val) {
    if (
$val == 'stop') {
        break;    
/* You could also write 'break 1;' here. */
    
}
    echo 
"$val<br />\n";
}

/* Using the optional argument. */

$i 0;
while (++
$i) {
    switch (
$i) {
        case 
5:
            echo 
"At 5<br />\n";
            break 
1;  /* Exit only the switch. */
        
case 10:
            echo 
"At 10; quitting<br />\n";
            break 
2;  /* Exit the switch and the while. */
        
default:
            break;
    }
}
?>

Changelog para o break
Versão Descrição
7.0.0 break fora de um laço ou de uma estrutura de controle switch agora é detectado em tempo de compilação, antes era em tempo de execução, e dispara um erro do tipo E_COMPILE_ERROR.
5.4.0 break 0; não é mais válido. Nas versões anteriores era interpretado como break 1;.
5.4.0 Removida a possibilidade de passar variáveis como argumentos numéricos (ex., $num = 2; break $num;)

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