Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Breaks in default case switches?

Tags:

switch ($var) {     case 0:         // Do something...         break;     case 1:         // Do something...         break;     default:         // Do something...         break; } 

I've seen some people use break at the end of the default case. Since the default case is the last case that's executed when triggered, is there any need to have a break there? I'm guessing it's just done out of common practice or is there another reason?

like image 952
user1307016 Avatar asked Aug 21 '12 03:08

user1307016


People also ask

Do default switches need breaks?

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Is default necessary in switch case PHP?

Switch cases should almost always have a default case. 2. To handle 'default' actions, where the cases are for special behavior.

Does PHP have a switch statement?

The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed.

Can we write 2 defaults in switch case?

There can be at most one default statement. The default statement doesn't have to come at the end. It may appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement.


1 Answers

There's no reason its required so long as the default is at the end of the switch statement. Note that the default doesn't need to be the last case: http://codepad.viper-7.com/BISiiD

<?php $var = 4; switch($var) {     default:         echo "default";         break;     case 4:         echo "this will be executed";         break; } 
like image 163
Lusitanian Avatar answered Oct 03 '22 15:10

Lusitanian