views:

69

answers:

3

A switch statement consists of "cases"...

But is there any "else" case for all other cases?

Have never found the answer to this...

ex:

 switch ($var){
   case "x":
       do stuff;
   break;
   case "y":
       do stuff;
   break;
   else: // THIS IS WHAT I WOULD LIKE
       do stuff;
   break;
 }
+7  A: 
default:
       do stuff;
break;

Typically the default clause should be at the very end of your other case clauses for general readability.

You may also want to reformat your break statements in your code to look like this:

 switch ($var){
   case "x":  // if $var == "x"
       do stuff;
       break;
   case "y":  // if $var == "y"
       do stuff;
       break;
   default:  // if $var != "x" && != "y"
       do stuff;
       break;
 }

Extra information on the switch statement available here and here.

Daniel May
+1 Short and sweet!
AntonioCS
+1  A: 

As Dan said but in complete form if it helps...

switch ($var) {
    case "x":
        // do stuff
        break;
    case "y":
        // do stuff
        break;
    default:
        // do "else" stuff...
}
Simon
NB no break clause required on final case, be that "default" or "case"...
Simon
but it is good practice to always put a `break` if your intention is not to fall-through.
phresnel
A: 

As the others said. Not though that default might also be at the beginning or somewhere wildly in the middle:

switch (foo) {
case 0: break;
default: break;
case 1: break;
};

Surely you should not do this if not justified.

phresnel
If you put default anywhere other that the bottom, any cases below it will be ignored.
Simon
@Simon: Why do you think that and don't try yourself? Here's what the standard says: 6.4.2/5 [stmt.switch]"When the switch statement is executed, its condition is evaluated and compared with each case constant. [...] If no case constant matches the condition, and if there is a default label,control passes to the statement labeled by the default label."
phresnel
@Simon: My fail, for some rason I was assuming C. But it PHP, it seems to be the same: http://de.php.net/manual/en/control-structures.switch.php#87959
phresnel