How is the ‘break’ used in PHP?

In PHP, the break keyword is used to terminate control structures such as switch, for, foreach, while, and do-while loops. When break is executed, the loop will immediately end, the program control flow will exit the loop body, and continue executing the code following the loop body. Break is typically used in conjunction with conditional statements to exit the loop when certain conditions are met.

Here are examples of using the break keyword in different control structures.

  1. Because of
  2. Take a pause
for ($i = 0; $i < 10; $i++) {
    if ($i == 5) {
        break;
    }
    echo $i . "\n";
}
  1. during
  2. “Take a break”
$i = 0;
while ($i < 10) {
    if ($i == 5) {
        break;
    }
    echo $i . "\n";
    $i++;
}
  1. change
  2. To fracture or shatter
$day = "Monday";
switch ($day) {
    case "Monday":
        echo "Today is Monday";
        break;
    case "Tuesday":
        echo "Today is Tuesday";
        break;
    // other cases...
}

In conclusion, the keyword ‘break’ is used to prematurely terminate the execution of a loop or switch statement.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds