The switch case construct is an alternative to using the if, elseif, else construct. The switch statement takes some expression and compares it to a set of values.
For example, let’s create a normal condition:
$a = 3; if($a==1) echo "1"; elseif($a==2) echo "2"; elseif($a==3) echo "3"; elseif($a==4) echo "4";
and now we will write down it already with use of switch:
$a = 3; switch($a) { case 1: echo "1"; break; case 2: echo "2"; break; case 3: echo "3"; break; case 4: echo "4"; break; default:// else echo "no number"; break; }
Alternative switch, operator match
Starting with version 8.0 PHP added support for another, similar construct – match. It allows you to optimize the switch construct. The match construct also takes an expression and compares it against a set of values.
For example, let’s say we have the following code:
$a = 2; switch($a) { case 1: $operation = "1"; break; case 2: $operation = "2"; break; default: $operation = "3"; break; } echo $operation;
now let’s write it down through match:
$a = 2; $operation = match($a) { 1 => "1", 2 => "2", default => "3", }; echo $operation;
unlike switch, the match construct returns some result. Therefore, after each comparable value, the => operator is placed, after which comes the returned result.
It is worth noting an important difference between the switch construction and match: switch compares only the value, but does not take into account the type of the expression. Whereas match also takes into account the type of the expression being compared.
Shorted if - ternary operator PHP. Code example
May 4, 2022