PHP Switch
A switch statement in PHP is a control structure that allows you to evaluate a variable against multiple possible values and execute different code based on which value it matches. It's similar to using multiple if...else if...else statements but is often more readable and can be more efficient.
Here's the basic syntax of a switch statement in PHP:
switch (variable) {
case value1:
// code to execute if variable == value1
break;
case value2:
// code to execute if variable == value2
break;
case value3:
// code to execute if variable == value3
break;
default:
// code to execute if variable doesn't match any case
break;
}
Example 1: Simple Switch Statement
<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "Today is Monday";
break;
case "Tuesday":
echo "Today is Tuesday";
break;
case "Wednesday":
echo "Today is Wednesday";
break;
default:
echo "Today is not Monday, Tuesday, or Wednesday";
break;
}
?>
Output:
Today is Tuesday
Example 2: Switch with Fall-Through
In some cases, you might want to execute the same code for multiple cases. You can do this by omitting the break statement for those cases.
<?php
$grade = 'B';
switch ($grade) {
case 'A':
case 'B':
case 'C':
echo "You passed!";
break;
case 'D':
case 'F':
echo "You failed!";
break;
default:
echo "Invalid grade.";
break;
}
?>
Output:
You passed!
Example 3: Switch with Expressions
You can also use expressions within the case labels.
<?php
$number = 2;
switch ($number) {
case 1 + 1:
echo "The number is 2";
break;
case 2 + 2:
echo "The number is 4";
break;
default:
echo "The number is neither 2 nor 4";
break;
}
?>
Output:
The number is 2
Example 4: Nested Switch Statement
You can also nest switch statements inside one another.
<?php
$fruit = "apple";
$color = "red";
switch ($fruit) {
case "apple":
switch ($color) {
case "red":
echo "You have a red apple";
break;
case "green":
echo "You have a green apple";
break;
default:
echo "You have an apple of unknown color";
break;
}
break;
case "banana":
echo "You have a banana";
break;
default:
echo "Unknown fruit";
break;
}
?>
Output:
You have a red apple
The switch statement is a powerful tool for managing multiple conditional branches, making your code more readable and maintainable.