Saturday, August 16, 2008

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

PHP F1



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

PHP F1



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.



 



To solve the previous problem we can extend our code with a default part. The code in this block works as the else block in case of the if satetement. So the complete switch statement will look like this:



Code:

  1. $x = 13;

  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. default:

  19. echo "Not recognized";

  20. break;

  21. }

PHP F1



The default case matches anything that wasn't matched by the other cases, and should be the last case. statement.

No comments: