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);

// src/Controller/Snippet/Snippet122Trait.php

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 = 0;
        $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;

        // That's it! 😁

        // With PHP 8 we would write: ——————————————————————————————————————————

        // $returnValue = match ($i) {
        //    0       => 4,
        //    1       => 6,
        //    2, 3    => 5,
        //    default => null,
        // };

        // Much more concise!
    }
}

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