Skip to content

Instantly share code, notes, and snippets.

@rafi
Created July 24, 2013 09:32
Show Gist options
  • Save rafi/6069208 to your computer and use it in GitHub Desktop.
Save rafi/6069208 to your computer and use it in GitHub Desktop.
99% of times a `switch` statement is a BAD idea
<?php
$preferences = [ 'c', 'e' ];
$params = [];
foreach ($preferences as $setting)
{
switch($setting)
{
case 'a':
$params[] = "-ie -ff -ch";
break;
case 'b':
$params[] = "true";
break;
case 'c':
$params[] = "-mtb";
break;
case 'd':
$params[] = "-mds";
break;
case 'e':
$params[] = "-mhp -mnt";
break;
}
}
<?php
$preferences = [ 'c', 'e' ];
$flags = [
'a' => '-ie -ff -ch',
'b' => 'true',
'c' => '-mtb',
'd' => '-mds',
'e' => '-mhp -mnt',
];
// Returns an array containing all the entries of `flags`
// which have keys that are present in `preferences`.
// Preferences values are flipped for key intersection.
$params = array_intersect_key($flags, array_flip($preferences));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment