PHP switch case statement


Home - Tutorials - Basics

In this tutorial I will show you with code eaxmples how to use the switch - case statement in PHP.

Step 1 - Switch case basics


PHP switch case statement


The switch case statement can be very usefull and makes your code more readable if you need to make a lot of decisions with the if - elseif - else statement. Let's suppose the following example where we use the if-else sollution:

Code:
  1. $x = 3;
  2. if ($x == 0){
  3. echo "0";
  4. } elseif ($x == 1){
  5. echo "1";
  6. } elseif ($x == 2){
  7. echo "2";
  8. } elseif ($x == 3){
  9. echo "3";
  10. } elseif ($x == 4){
  11. echo "4";
  12. } else {
  13. echo "Not recognized";
  14. }
In this code we compare the same variable with many different values using the if statement. However this is the case where we could use the switch - case control strucure as well like this:
Code:
  1. $x = 3;
  2. switch ($x){
  3. case 0:
  4. echo "0";
  5. break;
  6. case 1:
  7. echo "1";
  8. break;
  9. case 2:
  10. echo "2";
  11. break;
  12. case 3:
  13. echo "3";
  14. break;
  15. case 4:
  16. echo "4";
  17. break;
  18. }
Although the switch sollution doesn't result a shorter code but it is a bit easier to understand. However you have to take care of the break statements which works as a code block terminator.
This example is not exactly the same as the "if" version as for example in case of $x=10 this code prints nothing. To solve this we can extend our switch statement.




Next Step of PHP switch case statement


Tags: PHP switch case, PHP switch, PHP case, switch case, php, switch, case

PHP switch case statement - Table of contents
Step 1 - Switch case basics
Step 2 - Extend swich with default

F1 Site Family
AJAX F1
CSS F1
Database F1
Forex F1
Flash F1
HTML F1
JavaScript F1
PhotoShop F1
PHP F1
 

 
MaxTutorial
Monthly mortgage payment calculator
WebFormGenerator
Forex mini accounts

Total time: 0.0158