break out of if and foreach
To break out of a loop in PHP, you can use the break
statement. Here is an example of using break
to exit a foreach loop:
<?php
$items = array('apple', 'banana', 'cucumber');
foreach ($items as $item) {
if ($item == 'banana') {
break;
}
echo $item . "\n";
}
This will print "apple" and then exit the loop.
You can also use break
to exit nested loops by specifying the number of levels to break out of. For example:
<?php
$outer = ['a', 'b', 'c'];
$inner = ['x', 'y', 'z', 'target', 'w'];
foreach ($outer as $value) {
foreach ($inner as $innerValue) {
echo $innerValue . PHP_EOL; // Output the current value of $innerValue
if ($innerValue == 'target') {
break 2; // Exit both loops when the target value is found
}
}
}
echo 'Done!'; // Output a message after the loops complete
This will break out of both the inner and outer loops.