In PHP, the switch
statement provides an alternative way to control the flow of a program based on conditional logic. A switch
statement allows you to test a variable for equality against a series of values and execute different blocks of code based on the value of the variable.
Here is an example of using a switch
statement in PHP:
$fruit = "apple";
switch ($fruit) {
case "banana":
echo "Yellow fruit";
break;
case "apple":
echo "Red fruit";
break;
case "orange":
echo "Orange fruit";
break;
default:
echo "Unknown fruit";
}
In this example, the variable $fruit
is assigned the value "apple"
. The switch
statement checks the value of $fruit
against each of the case
statements. If the value of $fruit
matches one of the cases, the corresponding block of code is executed. In this case, the value of $fruit
matches the second case
statement, so the string “Red fruit” is printed to the screen. The break
statement is used to prevent the program from continuing to execute the subsequent case
statements.
If none of the case
statements match the value of $fruit
, the default
statement is executed. In this example, if the value of $fruit
were "pear"
, the default
statement would execute and the string “Unknown fruit” would be printed to the screen.
You can also use multiple values for a single case
statement:
$day = "Tuesday";
switch ($day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
echo "Weekday";
break;
case "Saturday":
case "Sunday":
echo "Weekend";
break;
default:
echo "Unknown day";
}
In this example, the variable $day
is assigned the value "Tuesday"
. The switch
statement checks the value of $day
against each of the case
statements. If the value of $day
matches one of the weekday
cases, the string “Weekday” is printed to the screen. If the value of $day
matches one of the weekend
cases, the string “Weekend” is printed to the screen. If the value of $day
does not match any of the cases, the default
statement is executed and the string “Unknown day” is printed to the screen.
By using the switch
statement in PHP, you can create conditional logic that allows your program to execute different blocks of code based on the value of a variable.