How to use the break statement in PHP?

Member

by dana , in category: PHP General , a year ago

How to use the break statement in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by shyann , a year ago

@dana 

In PHP, the break statement is used to exit from a loop or switch statement.


Here's an example of using the break statement in a loop:

1
2
3
4
5
6
for ($i = 0; $i < 10; $i++) {
  if ($i == 5) {
    break;
  }
  echo $i . "<br>";
}


In this example, the loop will iterate from 0 to 9. However, when $i equals 5, the break statement will be executed, causing the loop to exit. As a result, the output of this code will be:

1
2
3
4
5
0
1
2
3
4


Here's an example of using the break statement in a switch statement:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$day = "Monday";

switch ($day) {
  case "Monday":
    echo "Today is Monday";
    break;
  case "Tuesday":
    echo "Today is Tuesday";
    break;
  default:
    echo "Today is not Monday or Tuesday";
}


In this example, the switch statement checks the value of the $day variable. When $day equals "Monday", the code inside the first case statement will be executed. The break statement causes the switch statement to exit, so the code inside the second case statement and the default statement will not be executed. The output of this code will be:

1
Today is Monday


Member

by orpha , 6 months ago

@dana 

The break statement is used in PHP to exit from a loop or switch statement when a certain condition is met. It can be used in both for loops, while loops, do-while loops, and switch statements.


Here's how to use the break statement in PHP:

  1. Loop example:
1
2
3
4
5
6
for ($i = 0; $i < 10; $i++) {
  if ($i == 5) {
    break;
  }
  echo $i . "<br>";
}


In this example, the loop will iterate from 0 to 9. However, when $i equals 5, the break statement will be executed and the loop will exit. As a result, the output of this code will be:

1
2
3
4
5
0
1
2
3
4


  1. Switch statement example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$day = "Monday";

switch ($day) {
  case "Monday":
    echo "Today is Monday";
    break;
  case "Tuesday":
    echo "Today is Tuesday";
    break;
  default:
    echo "Today is not Monday or Tuesday";
}


In this example, the switch statement checks the value of the $day variable. When $day equals "Monday", the code inside the first case statement will be executed. The break statement causes the switch statement to exit, so the code inside the second case statement and the default statement will not be executed. The output of this code will be:

1
Today is Monday


In summary, the break statement is used to exit from a loop or switch statement in PHP. When the break statement is encountered, the program will immediately exit the loop or switch statement and continue executing the code after the loop or switch statement.