switch
` statement is a conditional statement in PHP that allows you to test a variable against a list of possible values and execute different code for each value. Here's the basic syntax of a `switch
` statement :switch (variable) {
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
case value3:
// Code to execute if variable equals value3
break;
default:
// Code to execute if variable doesn't equal any of the values
}​
variable
` is the variable that you want to test, and `value1
`, `value2
`, etc. are the possible values that you want to test against. The `case
` statements test if `variable
` equals each value in turn. variable
` equals `value1
`, then the code inside the first set of curly braces `{}
` is executed, and the `break
` statement causes the switch statement to exit. variable
` doesn't equal `value1
`, then the `case
` statement for `value2
` is tested, and so on. If none of the `case
` statements match, then the code inside the `default
` block is executed.switch
` statement to print the name of a day based on its corresponding numeric value :<?php
// This is a PHP program that uses a switch statement to print the name of a day based on its corresponding numeric value
$day = 2; // Tuesday
switch ($day) {
case 0:
echo "Sunday";
break;
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;
default:
echo "Invalid day";
}
?>
Tuesday
$day
` is assigned the value `2
`, which corresponds to Tuesday. The `switch
` statement then checks if `$day
` equals each of the possible values in turn. $day
` equals `2
`, the code inside the third set of curly braces `{}
` is executed, which prints the message "Tuesday" to the screen.$day
` had been assigned a value that didn't correspond to any of the possible values, the code inside the `default
` block would have been executed instead, which prints the message "Invalid day" to the screen.switch
` statements can be used to test a variable against a list of possible values and execute different code for each value.