PHP Switch
- In PHP, the
switch
statement is used as a control structure to perform different actions based on the value of an expression.
It is an alternative to a series of if-else
statements when you have multiple possible conditions to check against a single variable.
Syntax:
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// Additional cases as needed
default:
// Code to be executed if none of the cases match
break;
}
- Where the
switch
statement evaluates the givenexpression
. - The
case
statements define possible values for the expression. - If the expression matches a
case
value, the corresponding block of code is executed until abreak
statement is encountered. - If none of the
case
values match the expression, the code within thedefault
block (if present) is executed.
Example:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "It's the start of the week.";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
echo "It's a weekday.";
break;
case "Friday":
echo "TGIF!";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend.";
break;
default:
echo "Invalid day.";
}
?>
output:
It's the start of the week.
Code explanation:
- The value of $day is "Monday".
- The switch statement evaluates the expression and finds a match with the first case.
- The code within the corresponding case block is executed, which prints "It's the start of the week."
- The break statement ensures that the execution exits the switch statement after the matched case is executed.
Note: It's important to include the break statement at the end of each case block to prevent the code from falling through to the next case. If you want fall-through behavior, you can omit the break statement.