Web Programming TutorialsPHP Switch Statement

PHP Switch Statement

We are now familiar with the conditional/decision making statement, if…else. Today we will learn a similar decision making statement called switch-case in this PHP Switch Statement tutorial.

  • Switch-case statement:
    • Switch-case is another statement which works similar to if…elseif…else statement.
    • But in if…elseif…else there are many elseif statements used. If these statements are more in number, it becomes very difficult to trace out which block belongs to which elseif statement.
    • On the other hand the same thing is organized in a very systematic way which is called as switch-case.
    • Let us first see syntax of switch – case statement:
    • switch(variable or expression)
      {
      		case value1:    
                                   Statement(s);    //code to be executed
                                   break;
      		case value2:    
                                   Statement(s);    //code to be executed
                                   break;
      		case value3:    
                                   Statement(s);    //code to be executed
                                   break;
      		-
      		-
      		-
      			        break;
      		default:
                              Statement(s);    //code to be executed
                              break;
      
      }
      
    • In the above syntax of switch-case statement, a variable or expression is passed in the parenthesis of switch statement.
    • If an expression is passed in the parenthesis of switch statement, it is evaluated and the resultant value is passed further.
    • The words switch and case are the keywords.
    • The value passed in the switch statement is matched against the values of the case statement.
    • In the above syntax value1, value2 etc. are the case values. These can be an integer number, a string but not a float, because float values are not stored exactly in the memory. For example: a float number 4.9 can be stored as 4.900000 in the memory.
    • When the value is passed in the switch statement, the control enters the switch block. The opening and closing curly braces shown in the syntax above forms the switch block.
    • After entering the switch block the value is matched with the value of first case. If the passed value is equal to the case value, the statements written for that particular case are executed.
    • The keyword break is very important for each case. It throws the control out of the switch block as soon as the case execution is over, i.e. the execution terminates as soon as one case is matched and executed.
    • If the case is not matched, the control goes to the next case and so on.
    • This continues until a case value is matched with the passed value.
    • If no case is matched with the value passed, the default statement is executed and then the control comes out of the switch block.
    • default is a keyword and the statements written for it are executed when no case has matched with the passed value. It is same as else part in if…elseif…else statement.
    • Let us see an example of switch-case statement:
    • We will perform arithmetic operations in the switch-case statement.
    • Create a new folder named switch in the htdocs folder in xampp folder. Then open a new notepad++ document and save it as index.php in the newly created folder, switch.
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>switch-case statement</title>
      </head>
      <body>
      <h2>Demonstration of switch-case statement</h2>
      
      <?php
      
      echo "Options for arithmetic operations are:<br>";
      echo "1.Add&nbsp;&nbsp;&nbsp;&nbsp;2.Subtract<br>3.Multiply&nbsp;&nbsp;&nbsp;&nbsp;4.Divide<br><br>";
      $num1=60;
      $num2=40;
      $op=1;
      
      		switch($op)
      		{
      		case 1: echo "You selected option <strong>Add</strong>.<br><br>";
      				$ans=$num1+$num2;
      		        echo "<strong>".$num1." + ".$num2." = ".$ans."</strong>";
      				break;
      		case 2: $ans=$num1-$num2;
      		        echo "<strong>".$num1." - ".$num2." = ".$ans."</strong>";
      				break;	
      		case 3: $ans=$num1*$num2;
      		        echo "<strong>".$num1." * ".$num2." = ".$ans."</strong>";
      				break;
      		case 4: $ans=$num1/$num2;
      		        echo "<strong>".$num1." / ".$num2." = ".$ans."</strong>";
      				break;
      		default: echo "<strong>Have a good day.</strong>";
      		}
      ?>
      </body>
      </html>
      
    • In the above code we have shown the arithmetic options: Add, Subtract, Multiply and Divide with option numbers 1, 2, 3 and 4 respectively.
    • The   is the html code for non breakable space which leaves some space.
    • Two variables $num1 and $num2 contain numbers 60 and 40 respectively.
    • We have a variable $op with value 1 in it. This 1 is the option number of Add arithmetic operation given above.
    • This $op is passed to the switch statement.
    • The control enters the switch block and starts matching the value in $op variable to the first case value which is 1.
    • Both the values match and the code in the first case block is executed i.e. addition of two numbers is performed and it is printed on the webpage.
    • The keyword break terminates the execution and throws the control out of the switch block.
    • The output is shown below:
    • switch_case_output_1
      fig 1

    • Now if we change the value in $op from 1 to 3. It will perform multiplication operation.
    • If we change the value in $op1 to some other value like 5 which is not an option number, the default statement will be executed.
    • The output is shown below:
    • switch_case_output_2
      fig 2

  • Use of character/string in switch-case:
    • We can also use strings as case values in switch-case statement:
    • Let us see an example:
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>switch-case statement</title>
      </head>
      <body>
      <h2>Demonstration of switch-case statement</h2>
      
      <?php
      echo "List of fruits is as follows:<br>";
      echo "Which fruit do you like?<br>";
      echo "A. Apple &nbsp;&nbsp; B. Banana &nbsp;&nbsp; M. Mango &nbsp;&nbsp; O. Orange<br><br>";
      
      $op='M';
      		switch($op)
      		{
      		case 'A': echo "<strong>You like Apple.</strong>";
      				  break;
      		case 'B': echo "<strong>You like Banana.</strong>";
      				  break;
      		case 'M': echo "<strong>You like Mango.</strong>";
      				 break;
      		case 'O': echo "<strong>You like Orange.</strong>";
      				  break;
      		default: echo "<strong>You don't like any fruit specified above.</strong>";
      		break;
      		}
      ?>
      </body>
      </html>
      
    • Here, in the above code we have used string instead of integers as the case values.
    • In this code we have passed value M stored in the variable $op to switch statement.
    • This value matches with the case value M and executes its statements.
    • The break statement encountered after execution of echo statement throws the control out of switch block.
    • The output is shown below:
    • switch_case_output_3
      fig 3

  • Use of break statement in Switch-case:
    • The break statement is very useful in switch-case statement.
    • We can make its use in many different ways.
    • When we don’t give break after a case and if that case is executed, it will execute the code of next case also along with it.
    • Let us remove the break statement of case ‘A’ in the example of fruits above. The PHP code is shown below:
    • <?php
      echo "List of fruits is as follows:<br>";
      echo "Which fruit do you like?<br>";
      echo "A. Apple &nbsp;&nbsp; B. Banana &nbsp;&nbsp; M. Mango &nbsp;&nbsp; O. Orange<br><br>";
      
      $op='A';
      
      		switch($op)
      		{
      		case 'A': echo "<strong>You like Apple.</strong>";
      			    //break;	  
      		case 'B': echo "<strong>You like Banana.</strong>";
      				  break;
      		case 'M': echo "<strong>You like Mango.</strong>";
      				 break;
      		case 'O': echo "<strong>You like Orange.</strong>";
      				  break;
      		default: echo "<strong>You don't like any fruit specified above.</strong>";
      		break;
      		}
      ?>
      
    • Here, we have shown only the PHP code.
    • The variable $op contains value A and the break statement of case ‘A’ has been commented.
    • Now save the changes and see the output below:
    • switch_case_output_4
      fig 4

    • This happened because there was no break statement for case ‘A’.
    • Break statement is the interruption statement, since it did not interrupt the execution the code for next case i.e. case ‘B’ was also executed.
    • The case ‘B’ had break statement which then terminated the execution and threw the control out of the switch block.
    • This thing is used when we want 2 cases in switch case to execute the same code.
    • Suppose we take the same example as above and make slight changes in it as shown in the following code:
    • html>
      <head>
      <title>switch-case statement</title>
      </head>
      <body>
      <h2>Demonstration of switch-case statement</h2>
      
      <?php
      echo "List of fruits is as follows:<br>";
      echo "Which fruit do you like?<br>";
      echo "A. Apple &nbsp;&nbsp; B. Banana &nbsp;&nbsp; M. Mango &nbsp;&nbsp; O. Orange<br><br>";
      
      $op='o';
      
      		switch($op)
      		{
      		case 'a':
      		case 'A': echo "<strong>You like Apple.</strong><br>";
      				  break;
      		case 'b':
      		case 'B': echo "<strong>You like Banana.</strong><br>";
      				  break;
      		case 'm':
      		case 'M': echo "<strong>You like Mango.</strong><br>";
      				 break;
      		case 'o':
      		case 'O': echo "<strong>You like Orange.</strong><br>";
      				  break;
      		default: echo "<strong>You don't like any fruit specified above.</strong>";
      		break;
      		}
      ?>
      </body>
      </html>
      
    • In the above code we have added cases like case ‘a’, case ‘b’, case ‘m’ and case ‘o’ in the switch case.
    • These are small letter case values and we had capital letter case values already.
    • We have not given break statement after the small letter case because we want to execute the code of capital letter case when user chooses a small letter option.
    • I mean it is not sure always that if a user is asked to enter a letter, he/she will enter capital letter only. They can enter small letters also.
    • Imagine that a user wants to select orange option and he enters small letter ‘o’ instead of ‘O’ in capital letters. What will happen? The default statement will be executed. But even if he entered the right choice he got wrong answer just because he entered the string in small letters.
    • In such cases, considering all possibilities we can modify our code in the above given format taking into consideration small letter strings as well as capital letter strings.
    • In the above code, the variable $op has value ‘o’ i.e. ‘o’ in small letter.
    • When the control matches the case ‘o’, it finds no code there. But there is no break statement also. So the control goes to case ‘O’ and executes its code and comes out of switch block due to the break statement of case ‘O’.
    • The output is shown below:
    • switch_case_output_5
      fig 5

  • Nested switch-case statement:
    • A switch case statement can contain another switch case statement.
    • The inside switch statement is called inner switch statement and the switch statement containing it is called outer switch statement.
    • Let us see an example:
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>switch-case statement</title>
      </head>
      <body>
      <h4>Demonstration of switch-case statement</h4>
      
      <?php
      echo "List of Designations is as follows:<br>";
      echo "Select any one designation to know its salary.<br>";
      echo "M. Manager  &nbsp;&nbsp; a. Accountant &nbsp;&nbsp; S. Salesperson<br><br>";
      
      $op='M';
      
      	switch($op)
      	{
      	case 'm':
      	case 'M': echo "<strong>You selected Manager.</strong><br>";
      		     echo "Select the field of Manager.<br>";
      		     echo "1. Purchase Manager &nbsp;&nbsp; 2. Sales Manager<br><br>";
      	            $man=2;
      		     switch($man)
      		     {
      			case 1: 
      				echo "<strong>You selected Purchase Manager.</strong><br>";echo "Salary of Purchase Manager is Rs. 20000/-";
      				break;
      				case 2: 
      		              echo "<strong>You selected Sales Manager.</strong><br>";
      			       echo "Salary of Sales Manager is Rs. 18000/-";
      				break;
      		}
      	    break;
      	case 'a':
      	case 'A': echo "<strong>You like Banana.</strong><br>";
      	            break;
      	case 's':
      	case 'S': echo "<strong>You like Mango.</strong><br>";
      		     break;
      	default: echo "<strong>You selected an incorrect option.</strong>";
      		   break;
            }
      ?>
      </body>
      </html>
      
    • In the above example we have asked the user to choose the designation and know the salary for it.
    • If the user selects Manager Designation, he is again asked for the particular field of Manager and then provided the salary information.
    • This is done with the nesting of switch case statement in case ‘M’.
    • In the above example we have variable $op with value ‘M’.
    • When control enters the case ‘M’, it asks for the field of Manager and then executes the respective code.
    • The selected field manager option 2 is given in variable $man.
    • Actually we are selecting the options statically in this tutorial because we have till now not learned how to take input dynamically from user.
    • This value of $man variable is matched with the case 2 of inner switch statement.
    • We wanted to ask the user the field for manager when he selects the option Manager, so we used another switch statement in the case ‘M’ itself.
    • Each case in the inner switch also has break statement.
    • You can see a break statement outside the inner switch block too, this break statement is of case ‘M’.
    • Such inner switches can be written for every case.
    • The output of above code is given below:
    • switch_case_output_6
      fig 6

    Thus we finished learning the switch case statement along with its different forms in this PHP Switch Statement tutorial.

Previous articlePHP If…else Statement
Next articlePHP For Loop

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -