A switch statement in PHP is used to execute code based on the value of a variable. The syntax for a switch statement is as follows:
switch ($variable) {
case value1:
// Code to be executed if variable is equal to value1
break;
case value2:
// Code to be executed if variable is equal to value2
break;
// ...
default:
// Code to be executed if variable is not equal to any of the values above
break;
}
The variable in the switch statement is evaluated once, and the code for the first case that matches its value is executed. If the variable does not match any of the cases, the code in the default block is executed.
The break statement is used to prevent the code from executing the code for the next case. If the break statement is not used, the code will execute the code for all of the cases that match the value of the variable.
The default block is optional, but it is a good practice to include it in case the variable does not match any of the cases.
Here is an example of a switch statement:
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "It's Monday!";
break;
case "Tuesday":
echo "It's Tuesday!";
break;
case "Wednesday":
echo "It's Wednesday!";
break;
// ...
default:
echo "It's not a weekday!";
break;
}
This code will print the following output:
It's Tuesday!
I hope this helps!
No comments:
Post a Comment