Tsallaka zuwa abun ciki
Justice Tech School

Switch and Match In Depth

switch falls through without break and compares loosely. match is strict, needs no break, returns a value and throws UnhandledMatchError when nothing matches.

Example
$n = 2;
switch ($n) { case 1: echo "one\n"; break; case 2: echo "two\n"; break; default: echo "many\n"; }
$label = match (true) { $n < 2 => "low", $n < 5 => "mid", default => "high" };
echo $label, "\n";
try { echo match ($n) { 1 => "a" }; } catch (\UnhandledMatchError $e) { echo "no match\n"; }

Result

two
mid
no match

Exercise

End a switch case.

case 1: echo "a"; ;

Quiz Test

Does match compare strictly?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.