switch
switch ($day) {
case 'Sat':
case 'Sun':
$type = 'Weekend';
break;
default:
$type = 'Weekday';
}
- Uses loose comparison (
==) - Needs
break, or it falls through to the next case
match (PHP 8) — shorter and safer
$type = match ($day) {
'Sat', 'Sun' => 'Weekend',
default => 'Weekday',
};
| switch | match |
|---|---|
| statement | expression (returns a value) |
loose == |
strict === |
needs break |
no fall-through |
| no error if nothing matches | throws an error if nothing matches and no default |
match(true) for ranges
$grade = match (true) {
$marks >= 75 => 'A',
$marks >= 60 => 'B',
default => 'C',
};
Example
Example — Order status with match and switch
PHP
<?php
$status = 'shipped';
$label = match ($status) {
'pending' => '⏳ Waiting for payment',
'paid', 'processing' => '📦 Being packed',
'shipped' => '🚚 On the way',
'delivered' => '✅ Delivered',
default => 'Unknown status',
};
echo "Order: $label<br>";
$marks = 64;
$grade = match (true) {
$marks >= 75 => 'A',
$marks >= 60 => 'B',
$marks >= 33 => 'C',
default => 'F',
};
echo "Grade: $grade<br>";
$month = 2;
switch ($month) {
case 12:
case 1:
case 2:
echo 'Season: Winter';
break;
case 3:
case 4:
case 5:
echo 'Season: Summer';
break;
default:
echo 'Season: Monsoon or Autumn';
}
Output: Order: 🚚 On the way / Grade: B / Season: Winter