PHP switch case statement
In this tutorial I will show you with code eaxmples how to use the switch - case statement in PHP.
Tutorial info:
| Name: | PHP switch case statement |
| Total steps: | 1 |
| Category: | Basics |
| Level: | Beginner |
Bookmark PHP switch case statement
Step 1 - Switch case basics
PHP switch case statement
The switch case statement is a special format of conditional statements. It 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. Besides this a switch case code snippet can be better to debug, maintain and it can result a bit faster code. However it has one disadvantage, that programmer usually forgot about the break statements at the end of each instuction block.
The general code flow can be seen on the flow chart below.
Let's suppose the following example where we use the if-else sollution:
$x = 3;
if ($x == 0) {
echo "0";
} elseif ($x == 1) {
echo "1";
} elseif ($x == 2) {
echo "2";
} elseif ($x == 3) {
echo "3";
} elseif ($x == 4) {
echo "4";
} else {
echo "Not recognized";
}
$x = 3;
switch ($x) {
case 0:
echo "0";
break;
case 1:
echo "1";
break;
case 2:
echo "2";
break;
case 3:
echo "3";
break;
case 4:
echo "4";
break;
}
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.
Extend swich statement with default
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:
$x = 13;
switch ($x) {
case 0:
echo "0";
break;
case 1:
echo "1";
break;
case 2:
echo "2";
break;
case 3:
echo "3";
break;
case 4:
echo "4";
break;
default:
echo "Not recognized";
break;
}
The default case matches anything that wasn't matched by the other cases, and should be the last case statement. If you want more information about switch case statement you can visit the relevant wikipedia site and the official php manual pages.
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 |
