Refactoring a switch statement In this refactor we refactor a switch statement to an array approach https://www.php.net
requires: php any version

Most of the time we make our decisions in php with an if statement or a switch statement, sometimes this can be enhanced in an expressive way by using arrays.

Original code


        $language 'php';
        switch (
$language) {
            case 
'php':
                
$creator 'Rasmus Lerdorf';
                break;
            case 
'javascript':
                
$creator 'Brendan Eich';
                break;
            case 
'vue':
                
$creator 'Evan You';
                break;
            case 
'livewire':
                
$creator 'Caleb Porzio';
                break;
            case 
'laravel':
                
$creator 'Taylor Otwell';
                break;
        }

        

Refactored code


        $language 'php';
        
$creators = [
            
'php'        => 'Rasmus Lerdorf',
            
'javascript' => 'Brendan Eich',
            
'vue'        => 'Evan You',
            
'livewire'   => 'Caleb Porzio',
            
'laravel'    => 'Taylor Otwell'
        
];
        
$creator  $creators[$language];

        

Here is the output of the code

This is the output of original

Rasmus Lerdorf

This is the output of refactor

Rasmus Lerdorf

Want to learn more from LLoadout ?

LLoadout is your loadout for Laravel, helping you kickstart your development process. Besides this refactoring site we also make some cool packages and video tutorials !

Go to LLoadout on github