Switch case in php

Switch case is a type of decision making statement in php. Use php switch case statement option when you have many options and have to execute on of those. this is helpful where you have to use long blocks of if else if code

switch case in php syntax is given below:
PHP Code:
  1. <?php 
  2.  
  3. switch(condition){
  4.  
  5. case 1:
  6.  do something if case matched
  7. break;
  8.  
  9. case 2:
  10. do something if case matched;
  11. break;
  12.  
  13. default: 
  14.  do something if all the cases doesn't match;
  15.  
  16. }
  17.  
  18. ?>
You have to use php break; statement in order to quit parser from switch case. If you do not use break statement that code will keep on executing on next blocks. As you use break statement in case block that evaluates as true it will execute statement in that block and exit the switch php and will execute next line out of switch statement.

An example is given below that how to use switch statement in php. See it carefully and try.

First you need to create a form to get input from user you may also can use $_GET method but in simple i am using form to get input from user. create an html form name index.php


HTML Code:
  1. <html>
  2. <head>
  3. <title>Switch case in php tutorial</title>
  4. </head>
  5. <body>
  6. <form method="post" action="index.php">
  7. Enter any number from (1 to 3) : <input type="text" name="option" >  <input type="submit" name="submit" value="Check">
  8.  
  9. </form>
  10. <br />
  11. </body>
  12. </html>

Enter any number from (1 to 3) :
Now write php code for switch statement after html code.

PHP Code:
  1. <html>
  2. <head>
  3. <title>Switch case in php tutorial</title>
  4. </head>
  5. <body>
  6. <form method="post" action="index.php">
  7. Enter any number from (1 to 3) : <input type="text" name="option" >  <input type="submit" name="submit" value="Check">
  8.  
  9. </form>
  10. <br />
  11. </body>
  12. </html>
  13.  
  14.  <?php 
  15.  
  16.  if(isset($_POST['submit'])){
  17.  
  18. $option = $_POST['option'];
  19.  
  20.  switch($option){ 
  21.  
  22. case 1:
  23.              echo "Your Entered value is 1";
  24. break;
  25.  
  26. case 2: 
  27.               echo "Your Entered value is 2";
  28. break;
  29.  
  30. case 3:
  31.               echo "Your Entered value is 3";
  32.  
  33. default:
  34.             echo "Invalid entry in textbox";
  35. break;
  36.  
  37. ?>