Lesson 7: Switch case control structure

You already know how to use the nested if....else control structure. You can typically convert an if/else code to a switch case code, but the latter is the preferred one. We will see later why excellent programmers will prefer the switch case. So, the switch case is typically similar to the if/else. However, if you want to compare some expression or a variable, which when having different value runs a different piece of code, depending on the value, switch case comes in handy.

Now, suppose some bank application takes in user inputs as letters, such that

B: checks for balance,
W: withdraws,
T: transfers and
any other input is invalid entry

Hands on...
<?php


$input="W"; // this is the user input and is meant to change

if($input=="W"){
    echo "Withdraw";
}else if($input=="T") {
    echo "transfer";

}else if($input=="B") {
    echo "Show balance";

}else{//the default
    echo "Invalid entry";
}

?>

Run the code and try to change he user input and observe the output
Output:  Withdraw

The above code can be changed into a switch case

Syntax:

Swich (variable){

    case value 1:

        //to do code
    break;
   
    case value 2:
   
        //to do code
    break;
   
    case value 3 :
   
        //to do code
    break;
    .
    .
    .
    case value n :
        //to do code
    break;
   
    default:
   
        //to do code

}






Hands on.....

$input = "B";

Switch($input){

    case "B":
        echo "Show balance";
      
    break;
   
    case "T":
   
        echo "transfer";
    break;
   
    case "W":
   
        echo "Withdraw";
    break;
   
   
    default:
   
        echo "Invalid entry";

}

Run the code and try to change he user input and observe the output
Output: Show balance

Points to note:

Well, why switch case and not if/else?

I will appreciate if you left a comment or a question. The ext post will be a hot one. Do not miss.....











Labels: