Write a program to show day of the week using switch
Description: Write a PHP program to show the day of the week (for example Monday) based on a number, using the switch statement.
Rules and hints:
- The number can be from 1 to 7. Number 1 is Monday.
- If the number is not between 1 and 7, show an invalid number message in the
defaultcase.
PHP program to show the day of the week using switch
<?php
$day = 5;
switch ($day) {
case 1:
echo "It is Monday!";
break;
case 2:
echo "It is Tuesday!";
break;
case 3:
echo "It is Wednesday!";
break;
case 4:
echo "It is Thursday!";
break;
case 5:
echo "It is Friday!";
break;
case 6:
echo "It is Saturday!";
break;
case 7:
echo "It is Sunday!";
break;
default:
echo "Invalid number. Enter a number from 1 to 7.";
}
?>
Output:
Tutorials Class - Output Window
It is Friday!
How it works
switchcompares $day with every case.breakstops the switch after a match. Without it PHP would run the next cases too.defaultruns when no case matches.
The same with the PHP 8 match expression is in PHP match Expression.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Decision Making |
| PHP match Expression |
| Interview Questions & Answers |
|---|
| No Content Found. |