The statement switch
Basically, the switch
is a statement (in English statement) which allows the programmer to control the code flow. The switch
decides which "arms" will be executed based on a sequence of comparisons.
The switch
receives a principal value, which will be compared by the value placed on each case
. In all cases where the equality comparison is true, body of the case
will be executed.
An example:
<?php
$a = 5;
$b = 6;
$operator = '*';
switch ($operator) {
case '+':
echo 'Soma: ' . $a + $b;
break;
case '-':
echo 'Subtração: ' . $a - $b;
break;
case '*':
echo 'Multiplicação: ' . $a * $b;
break;
case '/':
// Cuidado com a divisão por zero.
echo 'Divisão: ' . $a / $b;
break;
default:
echo 'Operação inválida.';
}
Note that:
- The
switch
was used to change the code flow, depending on the variable $operator
.
- I used the
break
at the end of each case
(except in the default
). This is necessary because, without them, the switch
execute all the cases below the one that was truly evaluated. This behavior is called switch fallthrough.
It can be stated, therefore, that the main objective of a switch
is to control the flow of a code by comparing the equal value of the switch
to each case
.
Eventually, to replace a sequence of several if
/else
s by the declaration switch
, some programmers use switch (true)
as a ruse to make each case
is executed from a true value assessment (since each case
will be implicitly compared with true
, the expression passed to the switch
). However, this practice can be classified as "gambiarra", since it uses the switch
to do something that a sequence of if
/else
makes - the economy of lines is also rarely significant to the point of justifying such use.
The expression match
Unlike the switch
, the match
is a expression and therefore should always return a value. Therefore, the use of match
will now be recommended when you have to return a value.
Let’s look at another example of switch
, using an external variable to store the computed value:
<?php
$a = 5;
$b = 6;
$operator = '*';
$result = 0; // Armazenaremos o resultado das computações aqui.
switch ($operator) {
case '+': $result = $a + $b; break;
case '-': $result = $a - $b; break;
case '*': $result = $a * $b; break;
case '/': $result = $a / $b; break;
}
echo "O resultado da operação com o operador `$operator` é $result.";
Note that, as switch
was made for control flow, if we want to use it to compute a value, we have to keep a variable external. I did it with $result
, to store the result obtained by the implemented "calculator".
In this type of scenario, the switch
can be elegantly replaced by an expression match
:
<?php
$a = 5;
$b = 6;
$operator = '*';
$result = match ($operator) {
'+' => $a + $b,
'-' => $a - $b,
'*' => $a * $b,
'/' => $a / $b
};
echo "O resultado da operação com o operador `$operator` é $result.";
The code output is the same, but the difference is striking. Note that as match
is an expression, unlike switch
, the use of semicolons at the end of the expression is mandatory.
Note also that although the switch
allows the use of a default case, it ends up being optional (as I did in the example above). No match
, however, although you have the option of using a default case, in case you do not include it, an exception of type UnhandledMatchError
will be released if an expression without match is found. This shows that match
always return a value. Otherwise, you should handle this exception. More details in the documentation.
Differences
In general, the differences are:
- The
switch
is a statement and match
is an expression. Therefore, switch
by itself is not able to produce a value when being evaluated. Already match
, yes.
- No coercion of types. When comparing the values of each
case
, switch
uses the operator ==
(which makes automatic conversion of types). Already the match
, when making the evaluations, uses ===
(which does not coerce types).
- The
switch
allows several case
s are executed next (if you do not use the break
). It’s called fallthrough. In reverse, match
does not allow this, allowing only one arm to be evaluated at a time.
- The
match
is exhaustive. That is, if you find a condition that does not fit any of the arms, the exception UnhandledMatchError
. The switch
does not have something of the kind and allows not all possible cases to be dealt with (usually this occurs by failure of the programmer).
To page of RFC details each of these differences. Refer to for more details.
It’s far more powerful than a switch
. It also helps, in a way, more inattentive programmers, since it has "native defense mechanisms". However, I couldn’t find a use case that the switch
didn’t realize - it turns out switch
(when used to produce value) is a little more verbose, but this is rarely a problem.
Now it can be said that it is more correct to use switch
only to control flow. In the possibility of flow control having to generate a value, match
probably be the most appropriate.
Basically, functional programming has risen in popularity recently and Pattern matching is a very common feature among functional languages. Thus, PHP, probably not to "lag behind", seems to have decided copy these resources. Some say it is good, because it modernizes the language. Others may think it is not. In a way, both sides are right. Introducing this type of resource may facilitate certain use cases, but is it really worth introducing a new type of syntactic construction in the language?
The purpose of the switch is not to return results, but rather to control flow. In the languages where it is implemented correctly, the switch equates to
goto
, effectively creating a jumplist (and not theif
/elseif
, as laymen confuse) - In PHP it has always been a hazy thing. Thematch
probably corresponds to the current tendency of the language of "ah, this other language has, so we also need it", which in practice is just another expression. No matter how they use it, I had a way to do the same thing before, but it will please those who believe in the legend that "writing less is always better".– Bacco
It would be interesting to show that it is not a new idea but that it is something already existing a lot in functional languages and now imported to PHP, Pattern match.
– Augusto Vasques
Really, @Augustovasques, and the worst is that PHP has implemented in a "poor" way, without making use of all the power that the idea of Pattern match brings. See how it is more powerful in languages like Rust, Haskell, Elixir or even the proposal that can come to Javascript, as it allows, for example, "unpacking" values of more complex algebraic types (such as tuples, Records etc). Apparently PHP (yet? ) does not allow this.
– Luiz Felipe
As for functionality, it looks more like the various conditional ternaries (
c ? t : f
) chained– Costamilam