Using a closure to assign the result of a PHP switch-case to a variable

Published on 2020-12-04 • Modified on 2020-12-04

In this snippet, we will see how to use a closure to assign the result of a switch-case to a variable. In the closure we use early returns, so we don't have to use break statements. Note that this way to do is only pertinent when using PHP <= 7.4, if using PHP 8, you can now use the new match() function, which is precisely for this purpose.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet122Trait
{
    public function snippet122(): void
    {
        $i = random_int(0, 10);
        echo '$i = '.$i;
        echo "\n";

        $returnValue = (static function ($i) {
            switch ($i) {
                case 0:
                    return 4;
                case 1:
                    return 6;
                case 2:
                case 3:
                    return 5;
                default:
                    return null;
            }
        })($i);

        echo '$returnValue: '.$returnValue;
        echo "\n";

        // With PHP 8 we can use the new match() function ——————————————————————
        $returnValue = match ($i) {
            0 => 4,
            1 => 6,
            2, 3 => 5,
            default => null,
        };

        echo '$returnValue: '.$returnValue;

        // Much is more concise!

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!