PHP Switch Case Examples
Learn how to use php switch case statements with examples.
PHP switch case statement
When there is more than one alternative choice present, we use a switch case statement. PHP engine executes the case whose label matches the expression given in a switch parenthesis.
syntax:
switch(expression) {
case lable-1:
statements;
break;
case lable-2:
statements;
break;
...
default:
statements;
break;
}
Example code:
<?php
$day=4;
switch($day) {
case 1:
echo "Sunday"
break;
case 2:
echo "Monday"
break;
case 3:
echo "Tuesday"
break;
case 4:
echo "Wednesday"
break;
case 5:
echo "Thursday"
break;
case 6:
echo "Friday"
break;
case 7:
echo "Saturday"
break;
default:
echo "please enter valid input"
break;
}
?>
Steps:
- In the above code, we have created a variable called “day” and assigned a value of 4.
- Then, we created a switch statement to find the day.
- If there is a value of 1, then “Sunday” will be printed. Similarly, we have kept 7 days in sequence.
- Here, we have the value of 4 in the variable “day”, so “Wednesday” will be printed.
Conclusion
You can take input from the user and put it inside a switch statement, then the switch statement will execute according to the input the user gives.
I hope you find this guide useful and keep learning to code!
Click to learn: PHP