break out of if and foreach
To break out of a loop in PHP, you can use the break statement.
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:
How to break out of a loop in PHP?
php— editable, runs on the server
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:
How to break out of a loop in PHP using break?
<?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 completeThis will break out of both the inner and outer loops.