switch Statement
Choose one of many blocks of code to execute based on a value.
Syntax
switch ($value) {
case A:
// code
break;
default:
// code
}The switch statement compares one value against many possible case options. It is a cleaner alternative to a long chain of elseif statements.
Each case should end with break to stop execution falling through to the next case. The default case runs when nothing matches.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Route incoming HTTP method strings ('GET', 'POST', 'DELETE') to the correct handler function.
- Display a localised day name based on PHP's date('N') numeric weekday return value.
- Apply different shipping rates based on a customer's selected shipping zone code.
More examples
Basic switch on a string
switch compares a single value against multiple cases using loose equality and needs break to stop fall-through.
<?php
$method = 'POST';
switch ($method) {
case 'GET':
echo 'Fetching resource';
break;
case 'POST':
echo 'Creating resource';
break;
case 'DELETE':
echo 'Deleting resource';
break;
default:
echo 'Method not supported';
}Fall-through for grouped cases
Omitting break lets multiple cases share the same code block — here grouping Saturday and Sunday.
<?php
$day = (int) date('N'); // 1=Mon ... 7=Sun
switch ($day) {
case 6:
case 7:
echo 'Weekend';
break;
default:
echo 'Weekday';
}switch with return inside a function
Inside a function, return replaces break; the switch acts as a lookup table for zone-based pricing.
<?php
function shippingRate(string $zone): float {
switch ($zone) {
case 'domestic': return 4.99;
case 'eu': return 9.99;
case 'world': return 19.99;
default: return 0.0;
}
}
echo shippingRate('eu'); // 9.99
Discussion