The switch statement in PHP is used to perform different actions based on different conditions. It works as a cleaner and more readable alternative to multiple if...elseif statements when evaluating the same variable.
case labels for matchingbreak prevents fall-throughdefault handles unmatched cases
// Basic syntax of PHP switch statement
<?php
switch (expression) {
case value1:
echo "Matched value1";
break;
case value2:
echo "Matched value2";
break;
default:
echo "No match found";
}
?>
// Switch statement example using days
<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Tuesday":
echo "Second day!";
break;
case "Friday":
echo "Weekend is near!";
break;
default:
echo "Just another day.";
}
?>
The variable $day is compared against each case. When the value matches "Tuesday", the corresponding message is printed and execution stops due to the break statement.
Change the value of $day below to see how the switch statement reacts!
You can dynamically change the value of $day and reload the PHP file to observe how different cases are triggered based on the input.
switch when comparing a single variabledefault casebreak after each caseswitch_example.php$fruit with different valuesswitch to display messages for each fruit