Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The switch statement in PHP is a powerful tool for making decisions in your code. It is used to execute different blocks of code based on the value of a single expression. Instead of writing multiple if-else statements, you can simplify your code using switch.
In this article, we will discuss what a switch statement is, how it works, its syntax, and see examples to understand it better.
PHP switch Statement
The switch statement is a control structure in PHP that evaluates a given expression and matches it against multiple cases. Each case represents a potential value for the expression. When a match is found, the corresponding block of code is executed. If no match is found, an optional default block can be executed as a fallback.
Flowchart of switch Statement
Below is the flow of how a switch statement works:
The expression is evaluated.
The value is compared with the case values one by one.
If a match is found, the associated code block is executed.
The break statement stops further comparisons.
If no match is found, the default block is executed (if provided).
Syntax
The syntax of the switch statement in PHP is:
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
case value3:
// Code to execute if expression matches value3
break;
default:
// Code to execute if no case matches
break;
}
Explanation:
switch (expression): The expression is evaluated once.
case value1, value2, etc.: Each case is checked against the value of the expression.
break: Stops execution of further cases once a match is found.
default: (Optional) Executes when no cases match the expression.
Examples
Example 1: Basic switch Statement
<?php
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid day";
break;
}
?>
You can also try this code with Online PHP Compiler
Explanation: The value of $grade is "B." Since case "B": is grouped with case "A": and case "C":, the code prints "You passed."
PHP Switch Statement with Character
The PHP `switch` statement can be used with characters to make decisions based on specific character values. This is particularly useful when you want to perform different actions depending on a single character input. Let’s understand it step by step.
Syntax of Switch Statement with Character
The basic syntax of a `switch` statement in PHP is:
switch ($variable) {
case 'value1':
// Code to execute if $variable matches 'value1'
break;
case 'value2':
// Code to execute if $variable matches 'value2'
break;
default:
// Code to execute if $variable doesn't match any case
}
Here, `$variable` is the character you want to evaluate, & each `case` represents a possible value of that character. The `break` statement ensures that once a match is found, the code stops checking other cases. The `default` case is optional & runs if no match is found.
Example: Using Switch with a Character
Let’s say you want to check a user’s input for a single character & perform actions based on that character:
<?php
$grade = 'A'; // Assume this is the user's input
switch ($grade) {
case 'A':
echo "Excellent! You scored an A.";
break;
case 'B':
echo "Good job! You scored a B.";
break;
case 'C':
echo "You passed with a C.";
break;
case 'D':
echo "You need to improve. You scored a D.";
break;
case 'F':
echo "Sorry, you failed.";
break;
default:
echo "Invalid grade entered.";
}
?>
You can also try this code with Online PHP Compiler
1. Variable Initialization: We start by assigning a character (`'A'`) to the variable `$grade`.
2. Switch Statement: The `switch` statement checks the value of `$grade`.
3. Case Matching: If `$grade` matches any `case` (like `'A'`, `'B'`, etc.), the corresponding block of code is executed.
4. Break Statement: The `break` statement ensures that once a match is found, the program exits the `switch` block.
5. Default Case: If no match is found, the `default` block runs, displaying "Invalid grade entered."
Practical Use Case
This approach is useful in scenarios like grading systems, menu-driven programs, or any situation where you need to handle multiple conditions based on a single character input.
PHP Switch Statement with String
The PHP `switch` statement is not limited to characters; it can also work with strings. This makes it a versatile tool for handling text-based conditions in your code. Let’s understand how to use the `switch` statement with strings, step by step.
Syntax of Switch Statement with String
The syntax for using a `switch` statement with strings is the same as with characters. The only difference is that the `case` values are now strings instead of single characters.
switch ($variable) {
case 'string1':
// Code to execute if $variable matches 'string1'
break;
case 'string2':
// Code to execute if $variable matches 'string2'
break;
default:
// Code to execute if $variable doesn't match any case
}
Here, `$variable` is the string you want to evaluate, & each `case` represents a possible string value.
Example: Using Switch with a String
Let’s say you want to create a program that responds differently based on the day of the week. Let’s take a look at the code now:
<?php
$day = "Monday"; // Assume this is the user's input
switch ($day) {
case "Monday":
echo "Today is Monday. Start your week strong!";
break;
case "Tuesday":
echo "Today is Tuesday. Keep the momentum going!";
break;
case "Wednesday":
echo "Today is Wednesday. You're halfway through the week!";
break;
case "Thursday":
echo "Today is Thursday. Almost there!";
break;
case "Friday":
echo "Today is Friday. The weekend is near!";
break;
case "Saturday":
echo "Today is Saturday. Enjoy your weekend!";
break;
case "Sunday":
echo "Today is Sunday. Relax & recharge!";
break;
default:
echo "Invalid day entered.";
}
?>
You can also try this code with Online PHP Compiler
1. Variable Initialization: We assign a string (`"Monday"`) to the variable `$day`.
2. Switch Statement: The `switch` statement checks the value of `$day`.
3. Case Matching: If `$day` matches any `case` (like `"Monday"`, `"Tuesday"`, etc.), the corresponding block of code is executed.
4. Break Statement: The `break` statement ensures that once a match is found, the program exits the `switch` block.
5. Default Case: If no match is found, the `default` block runs, displaying "Invalid day entered."
Practical Use Case
Using `switch` with strings is helpful in scenarios like:
Building menu-driven programs where user inputs are text-based.
Handling different responses based on user input (e.g., chatbot responses).
Managing states or modes in an application (e.g., "active", "inactive", "pending").
PHP Switch Statement is Fall-Through
One important behavior of the PHP `switch` statement is its fall-through nature. This means that if a `case` matches & there’s no `break` statement, the code will continue executing the next `case` statements until it finds a `break` or reaches the end of the `switch` block.
What is Fall-Through?
In a `switch` statement, when a `case` matches the value of the variable, the code execution starts from that `case`. If there’s no `break` statement, PHP will continue executing the code for the subsequent `case` blocks, even if they don’t match the variable’s value. This is called fall-through.
Example: Demonstrating Fall-Through
Let’s look at an example to understand this properly:
<?php
$number = 2; // Assume this is the user's input
switch ($number) {
case 1:
echo "Number is 1. <br>";
case 2:
echo "Number is 2. <br>";
case 3:
echo "Number is 3. <br>";
case 4:
echo "Number is 4. <br>";
default:
echo "Number is not between 1 & 4. <br>";
}
?>
You can also try this code with Online PHP Compiler
1. Variable Initialization: We assign the value `2` to the variable `$number`.
2. Switch Statement: The `switch` statement checks the value of `$number`.
3. Case Matching: Since `$number` is `2`, the code execution starts from `case 2`.
4. Fall-Through Behavior:
- There’s no `break` statement after `case 2`, so PHP continues executing the code for `case 3`, `case 4`, & the `default` block.
- As a result, all the `echo` statements after `case 2` are executed, even though `$number` is not `3`, `4`, or in the `default` case.
Output of the Code
The output of the above code will be:
Number is 2.
Number is 3.
Number is 4.
Number is not between 1 & 4.
Practical Use Case
The fall-through behavior can be helpful in certain scenarios, like:
Grouping multiple cases that should execute the same code.
Creating a cascading effect where multiple conditions lead to a single outcome.
For example, if you want to handle multiple cases in the same way, you can write:
<?php
$day = "Monday"; // Assume this is the user's input
switch ($day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
echo "It's a weekday. Time to work!";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend. Time to relax!";
break;
default:
echo "Invalid day entered.";
}
?>
You can also try this code with Online PHP Compiler
Here, all weekdays are grouped together, & the same message is displayed for any weekday.
PHP Nested Switch Statement
A nested `switch` statement is when you place one `switch` statement inside another. This allows you to handle more complex decision-making scenarios where you need to evaluate multiple levels of conditions.
Why Use Nested Switch Statements?
Nested `switch` statements are useful when you have hierarchical or multi-level conditions. For example, you might want to evaluate a primary condition first & then, based on that, evaluate a secondary condition. This approach keeps your code organized & readable.
Syntax of Nested Switch Statement
The syntax for a nested `switch` statement is very easy. You simply place one `switch` statement inside the `case` block of another `switch` statement.
switch ($variable1) {
case 'value1':
switch ($variable2) {
case 'subvalue1':
// Code to execute if $variable2 matches 'subvalue1'
break;
case 'subvalue2':
// Code to execute if $variable2 matches 'subvalue2'
break;
default:
// Code to execute if $variable2 doesn't match any case
}
break;
case 'value2':
// Code to execute if $variable1 matches 'value2'
break;
default:
// Code to execute if $variable1 doesn't match any case
}
Example: Using Nested Switch Statements
Let’s say you’re building a program to determine the type of meal based on the day of the week & the time of the day. Let’s take a look at the code now:
<?php
$day = "Monday"; // Primary condition
$time = "Morning"; // Secondary condition
switch ($day) {
case "Monday":
switch ($time) {
case "Morning":
echo "It's Monday morning. Have a healthy breakfast!";
break;
case "Afternoon":
echo "It's Monday afternoon. Time for a light lunch!";
break;
case "Evening":
echo "It's Monday evening. Enjoy your dinner!";
break;
default:
echo "Invalid time entered for Monday.";
}
break;
case "Tuesday":
switch ($time) {
case "Morning":
echo "It's Tuesday morning. Start your day with a workout!";
break;
case "Afternoon":
echo "It's Tuesday afternoon. Grab a quick snack!";
break;
case "Evening":
echo "It's Tuesday evening. Relax & enjoy your meal!";
break;
default:
echo "Invalid time entered for Tuesday.";
}
break;
default:
echo "Invalid day entered.";
}
?>
You can also try this code with Online PHP Compiler
1. Primary Condition: The outer `switch` statement evaluates the value of `$day`.
2. Secondary Condition: For each `case` in the outer `switch`, there’s an inner `switch` statement that evaluates the value of `$time`.
3. Case Matching:
- If `$day` is `"Monday"`, the inner `switch` checks the value of `$time` & executes the corresponding block of code.
- Similarly, if `$day` is `"Tuesday"`, the inner `switch` evaluates `$time` & executes the appropriate code.
4. Break Statements: Each `case` block in both the outer & inner `switch` statements ends with a `break` to prevent fall-through.
5. Default Cases: Both the outer & inner `switch` statements have `default` cases to handle invalid inputs.
Output of the Code
If `$day` is `"Monday"` & `$time` is `"Morning"`, the output will be:
It's Monday morning. Have a healthy breakfast!
If `$day` is `"Tuesday"` & `$time` is `"Evening"`, the output will be:
It's Tuesday evening. Relax & enjoy your meal!
Practical Use Case
Nested `switch` statements are useful in scenarios like:
Building multi-level menu systems.
Handling hierarchical data (e.g., categories & subcategories).
Evaluating complex conditions with multiple dependencies.
Frequently Asked Questions
What is a switch statement in PHP?
A switch statement in PHP evaluates an expression and executes a block of code based on the matching case value. It is used as a replacement for multiple if-else conditions.
What happens if I don’t use break in a switch statement?
If you don’t use break, the execution will continue to the next case and subsequent cases until a break is encountered or the switch ends. This is called "fall-through."
What is the purpose of the default case in a switch statement?
The default case is executed when none of the specified case values match the expression. It is optional but useful for handling unexpected values.
Conclusion
The switch statement in PHP is a simple and effective way to handle multiple conditions. It helps make your code more readable and organized compared to using multiple if-else statements. By learning its syntax and features, you can create efficient programs that evaluate an expression and perform specific actions based on its value.