About Lesson
Switch Statement in PHP
The switch
statement is used when we have many possible conditions to check, and we want a cleaner way than writing multiple if...elseif...else
.
Syntax:
switch (variable) {
case value1:
// Code to execute if variable == value1
break;
case value2:
// Code to execute if variable == value2
break;
case value3:
// Code to execute if variable == value3
break;
default:
// Code to execute if no case matches
}
Important Points:
switch
checks a variable/expression against multiplecase
values.- If a match is found, that block of code runs.
break
is used to stop execution of the switch.- If no match is found, the
default
block runs.
Example1: Day of the Week
PHP
<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
case "Wednesday":
echo "Today is Wednesday.";
break;
default:
echo "Not a valid day.";
}
?>
Explanation:
$day = "Tuesday"
- Switch checks each case.
- Matches
Tuesday
, so output:Today is Tuesday.
break
prevents checking the rest.
Example2: Multiple Cases (Grouped Cases)
You can combine multiple cases to perform the same action.
PHP
<?php
$day = "Saturday";
switch ($day) {
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "It's a weekday.";
}
?>
Explanation:
- If
$day
isSaturday
orSunday
→ Output:It's the weekend!
- Else →
It's a weekday.
Example3: HTML + PHP
You can combine multiple cases to perform the same action.
PHP
<!DOCTYPE html>
<html>
<head>
<title>Switch Example</title>
</head>
<body>
<form method="post">
Enter a number (1-3): <input type="number" name="num">
<button type="submit">Check</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num = $_POST['num'];
switch ($num) {
case 1:
echo "You selected One.";
break;
case 2:
echo "You selected Two.";
break;
case 3:
echo "You selected Three.";
break;
default:
echo "Invalid choice.";
}
}
?>
</body>
</html>
Difference between if-elseif and switch:
if-elseif | switch |
---|---|
Can check complex conditions (>, <, &&, | |
Good for ranges and logical conditions | Good for exact matches |
Slightly harder to read with many conditions | Cleaner and easier with multiple values |