Making PHP 8.0’s match Expression more Configurable using Anonymous Functions

Old way of mapping out pathways

        $map = [
            'one' => 'A',
            'two' => 'A',
            'three' => 'A',
            'four' => 'B',
            'five' => 'B',
            'six' => 'B',
            'seven' => 'C',
        ];
        $default = 'D';

        $type = 'one';
        
        $resolution = $map[$type] ?? $default;

Storing a match in a variable

        $map = fn($type) => match ($type) {
            'one', 'two', 'three' => 'A',
            'four', 'five', 'six' => 'B',
            'seven' => 'C',
            default => "D",
        };

Storing a match in an array config. This may be more viable within frameworks.

example.php

        return [
            'map' => fn($type) => match ($type) {
                'one', 'two', 'three' => 'A',
                'four', 'five', 'six' => 'B',
                'seven' => 'C',
                default => "D",
            }
        ];
$exampleMap = config('example.map');
$type = 'one';

$resolution = $exampleMap($type);

Leave a comment

Your email address will not be published. Required fields are marked *