31
loading...
This website collects cookies to deliver better user experience
$expression = strpos("PHP is great", "PHP");
$resultOfExp = match($expression) {
0 => "Sentence starts with PHP",
9 => "Sentence ends with PHP",
'default' => "Sentence doesn't start or end with PHP"
}
match
is a method that accepts an expression that computes to different values. Note that, $expression could be anything, a function call or comparison operator. In our example above, we have made a simple function call to strpos
which returns the index of the second string in the first string.switch($expression) {
case 0:
$resultOfExp = "Sentence starts with PHP";
break;
case 9:
$resultOfExp = "Sentence ends with PHP";
break;
default:
$resultOfExp = "Sentence doesn't start or end with PHP"
}
$resultOfExp
. As a result, we are prone to errors and our code could easily end up unreadable.Switch Statement | Match Expressions |
---|---|
Loose type comparison. For example ($a == $b) | Strict type comparison. For example ($a === $b) |
Doesn’t return a value. Hence we have to assign the result over and over again. | The result of the expression is returned. Therefore we assign to our variable only once. |
Each case has multiple commands or multiple lines of code. | Only one expression per case. |
Finally, a switch statement requires an unnecessary and verbose break statement. | Whereas, match expressions do not need any additional verbose statement. |