Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Switch to Array

so I have a function that handles various other functions, and I use a switchstatement to handle these functions with cases and breaks.

It all works fine. Would it be possible for me to change this into an array with keys?

Here's the code

switch ($intMultiFun) {
    case "a":
        handle a function
        break;
    case "b":
        handle a function
        break;
    case "c":
        handle a function
        break;
    case "d":
        handle a function
        break;
}
like image 418
user2524169 Avatar asked Jul 06 '26 10:07

user2524169


2 Answers

$map = array(
 'a' => 'a_func_name',
 'b' => 'b_func_handler_name',
  ...
);

if (array_key_exists($intMultiFun, $map)) {
   call_user_func($map[$intMultiFun]); // optionally you can pass parameters too
}
like image 115
Gavriel Avatar answered Jul 10 '26 06:07

Gavriel


You're looking for in_array(), it seems:

if(in_array($intMultiFun, ['a', 'b', 'c', 'd']))
{
   //handle a function
}

-short arrays syntax was introduced in PHP>=5.4, so in lower versions that will be

if(in_array($intMultiFun, array('a', 'b', 'c', 'd')))
{
   //handle a function
}

Edit

If functions would be different, then you should hold them in array, like:

$rgFunctions = ['a'=>'funcA', 'b'=>'funcB', 'c'=>'funcC', 'd'=>'funcD'];
if(array_key_exists($intMultiFun, $rgFunctions) &&
   function_exists($rgFunctions[$intMultiFun]))
{
   $mResult = call_user_func($rgFunctions[$intMultiFun]);
}
like image 29
Alma Do Avatar answered Jul 10 '26 05:07

Alma Do