break

suggest change
The break keyword immediately terminates the current loop.

Similar to the continue statement, a break halts execution of a loop. Unlike a continue statement, however, break causes the immediate termination of the loop and does not execute the conditional statement again.

$i = 5;
while(true) {
    echo 120/$i.PHP_EOL;
    $i -= 1;
    if ($i == 0) {
        break;
    }
}

This code will produce

24
30
40
60
120

but will not execute the case where $i is 0, which would result in a fatal error due to division by 0.

The break statement may also be used to break out of several levels of loops. Such behavior is very useful when executing nested loops. For example, to copy an array of strings into an output string, removing any \# symbols, until the output string is exactly 160 characters

$output = "";
$inputs = array(
    "#soblessed #throwbackthursday",
    "happy tuesday",
    "#nofilter",
    /* more inputs */
);
foreach($inputs as $input) {
    for($i = 0; $i < strlen($input); $i += 1) {
        if ($input[$i] == '#') continue;
        $output .= $input[$i];
        if (strlen($output) == 160) break 2; 
    }
    $output .= ' ';
}

The break 2 command immediately terminates execution of both the inner and outer loops.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Loops:
* Loops
* break
* for
* while

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR