Is there any "Else Case" in the switch function to use?

31,239

Solution 1

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.

Solution 2

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...
}

Solution 3

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.

Share:
31,239
Admin
Author by

Admin

Updated on June 23, 2020

Comments

  • Admin
    Admin almost 4 years

    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;
     }