PHP 8 Match Expression Example

Hello devs,

In this PHP tutorial, I will discuss PHP 8 match expression. PHP 8 released this amazing feature. This PHP match expression branches evaluation based on an identity-check of a value.

This is similar to a PHP switch statement, a match the expression has a subject expression that is compared against multiple alternatives. Unlike switch, This will evaluate to a value much like ternary expressions.

Let’s see an example using switch :

switch (1) {
    case 0:
        $result = 'Foo';
        break;
    case 1:
        $result = 'Bar';
        break;
    case 2:
        $result = 'Baz';
        break;
}
 
echo $result; // Bar

 

The same thing could be achieved using the new match expression like below:

$result = match (1) {
    0 => 'Foo',
    1 => 'Bar',
    2 => 'Baz',
};
 
echo $result; // Bar

 

See the details about PHP match expression. Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js