In php, a switch case statement tests a variable against multiple values and when the switch statement finds a match, it executes code in the case block.
$variable = "apple";
switch($variable) {
case "apple":
echo "The variable is apple.";
break;
case "banana":
echo "The variable is banana.";
break;
default:
echo "The variable is something else.";
break;
}
//Output:
The variable is apple.
When working in php, being able to control the flow of data in our programs and perform specific operations based on the values of variables is very important.
When dealing with complex situation in our php programs, we can use switch case statements to control the flow of data based on the value of a variable.
A switch case statement is similar to an if-elseif-else statement and tests a variable against a series of values until it finds a match.
When it finds a match, php executes the block of code corresponding to that match.
The correct syntax for a switch case statement in php is shown below in a simple example.
$variable = "apple";
switch($variable) {
case "apple":
echo "The variable is apple.";
break;
case "banana":
echo "The variable is banana.";
break;
default:
echo "The variable is something else.";
}
//Output:
The variable is apple.
php Switch Case Statement Where You Have the Same Value for Multiple Cases
There are some cases when using a switch case statement where you want to take the same action for multiple cases.
In this case, where you want to do the same action for multiple cases, you just need to make sure not to use the ‘break’ keyword. If there is no ‘break’ after a ‘case’, the code will keep executing.
Below is a simple example of showing a switch case statement where you have the same value for multiple cases.
switch ($num) {
case 0:
case 1:
case 2:
$message = '0-2';
break;
case 3:
$message = '3';
break;
default:
$letter = 'not in 0-3';
break;
}
Hopefully this article has been useful for you to learn how to create a switch case statement in your php code.