Conditionals · Lesson 5 of 6
switch Statement
Select a branch from a value with switch.
Lesson
A switch statement is useful when one value is matched against several known cases. Remember break to prevent execution continuing into later cases. Use a default branch for unexpected values. For new code, match is another option when you want an expression with stricter matching.
This example maps a weekday number to a short label.
Further guidance
Test each branch with a normal value, a boundary value, and an unexpected value. Order range checks from specific to broad, make the fallback behavior intentional, and keep related decisions readable. A condition should use validated data rather than an untrusted request value directly.
Practice task: Create a fresh example for switch Statement. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
switch Statement
PHP
$day = 6;
switch ($day) {
case 6:
case 7:
echo 'Weekend';
break;
default:
echo 'Weekday';
}
Expected output
Weekend
Key points
- Select a branch from a value with switch.
- Test boundary cases for every conditional branch.
- Keep fallback behavior explicit and use validated values.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.