Look at this switch statement . its boring right?
<?php
$day = "Wednesday";
switch ($day) {
case "Monday":
echo "Start of the week, grab some coffee!";
break;
case "Tuesday":
case "Wednesday":
echo "Midweek vibes, keep coding!";
break;
case "Thursday":
echo "Almost there, you got this!";
break;
case "Friday":
echo "Hello, weekend! Time to celebrate!";
break;
default:
echo "It's the weekend or an unknown day, take a break!";
}
?>
here we are saying $day is Wednesday . The case checking for each of the date and print a message . Its so huge and boring to write . There must have a better way !! Here’s the same example using the match
statement in PHP (available from PHP 8.0 and later):
<?php
$day = "Wednesday";
$message = match ($day) {
"Monday" => "Start of the week, grab some coffee!",
"Tuesday", "Wednesday" => "Midweek vibes, keep coding!",
"Thursday" => "Almost there, you got this!",
"Friday" => "Hello, weekend! Time to celebrate!",
default => "It's the weekend or an unknown day, take a break!",
};
echo $message;
?>
n this version, the match
statement provides a more concise syntax to achieve the same result as the switch statement. The arrow (=>
) is used to associate each case with its corresponding message, and the default
case is handled with default
.