What are the differences between match and switch in PHP8?

Asked

Viewed 304 times

9

PHP 8 looks like have already been launched, with a series of changes and new things. Among the changes, they created the expression match.

I saw that she reminds a little of the old and traditional switch, but it seems a little different.

Example of documentation:

$age = 23;

$result = match (true) {
    $age >= 65 => 'senior',
    $age >= 25 => 'adult',
    $age >= 18 => 'young adult',
    default => 'kid',
};

var_dump($result); // string(11) "young adult"

I’d like to know:

  • What are the main differences between switch and match?
  • This functionality replaces switch or it’s just different?
  • 8

    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 the if / elseif, as laymen confuse) - In PHP it has always been a hazy thing. The match 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".

  • 3

    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.

  • 2

    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.

  • 2

    As for functionality, it looks more like the various conditional ternaries (c ? t : f) chained

2 answers

10


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/elses 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 cases 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?

  • 4

    I don’t know, but, I think the network is very biased with PHP and also who develops with PHP, when there are added features there are always people criticizing that this is not good, that it makes no sense, that writing less is not always the best, But, the people who really like PHP and use really liked the latest news, I just wanted to confirm this, because I see here not generally criticizes too unfounded. I liked your answer +1.

  • 4

    @novic, thanks. : ) I wouldn’t say it’s prejudice, but yes maybe (I can’t speak for anyone) concern. Generally, I understand who liked the addition (I myself hope for the introduction of something similar in JS) can use the new feature to make codes more expressive and short. However, at least as far as I could see, the Pattern matching PHP is a bit limited, q may also not justify its addition. I couldn’t see any example of match for nested structures (see last example in previous link) in PHP.

  • 3

    It may be possible and it just hasn’t been documented, but I haven’t had time to test it yet. If possible, I will update this response. But I am confident that, at least currently, the match PHP (unfortunately) can only be used in this type of simple evaluation.

  • 1

    The PHP community that I participate in, because I program since version 3 liked a lot I still do not use version 8 because it is still new and everything new needs time to understand. A resource of Typescript in the declaration in the property builder I found interesting and useful. I still don’t think it’s a concern, because, imagine you’re just not using in your code the new feature.

  • 5

    @Exact Luizfelipe, the biggest problem is that a half-mouth functionality was made without solving the original problems of switch, and that it does not introduce anything important into the language. The bigger problem is that as most language users have no commitment to right, they applaud anything. The biggest problem of PHP is the uncompromising part of the users, and not the language itself (has face that uses it for I don’t know how many years and does not leave the same mentality, is to cry). Only thanks to that, the language has been losing what made it advantageous, and is trying to become something else.

  • 4

    Now, it’s no use if I want to prolong this much in the comments, because the time I have using PHP is greater than the age of the vast majority of users of the site, so to be able to situate everyone, this space here would not be suitable (and nor is it my function)So, each one uses how they want, do what. I just think it’s a shame for the wasted potential. Even more than PHP use professionally, among other languages, so it is not just a matter of taste, has practical aspect, and legitimate concern.

  • Here for example the Laravel community fled, because of contrary manifestations and that only attack the vast majority of developers, the trial is a trivial form on the network and maybe this is a factor where one knows everything and the others know nothing. It is worth remembering that always had this with PHP the demoralization of people and the language itself.

  • 3

    I see in general people who understand computing, programming languages, criticizing everything bad about PHP, JS, Python and Java, C#, C++, and any other language that people use and that it’s a conceptual error to do that, or at least it’s in bad taste. I don’t expect the same level of criticism among those who don’t really understand how mechanisms should behave. And I don’t expect the PHP community to criticize something that the language does wrong. not only for this reason already mentioned, but also because with the large amount would be admission to be masochistic.

Show 3 more comments

0

The differences: The match is a shorter expression that you don’t need to use break in its structure, you do not need to necessarily declare variables for each case, to return something, just tell directly what it will return, it can combine different expressions using comma, it is No type coercion, ie it is as if it used === instead of ==, Example:

$message = match ($statuscode) {
   200, 301 => null,
   404 => 'not found',
   500 => 'ERROR',
   default => 'unknown status code',
};

Unknown values will throw errors:

$statuscode = 1000000
$retorno = match($stauscode){
   500000 => 'Meio Milhão',
};

In that case you will return UnhandledMatchError

You can see more details and specifics about match on: https://www.php.net/manual/en/control-structures.match.php

Already the switch is much more flexible, especially at the level of comparison, it makes a series of comparisons to decide which code snippets, 'Arms', will be executed, in it you have to use break, so that when a condition is met the switch execution stops. Example:

switch (true) {
case ($a === true):
    echo '$a is true';
    break;
case ($a === false):
    echo '$a is false';
    break;
case ($a === 0):
    echo '$a is 0';
    break;
}

You can see more about switch in the PHP documentation: https://www.php.net/manual/en/control-structures.switch.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.