Can you store a function in a PHP array?

The recommended way to do this is with an anonymous function:

$functions = [
  'function1' => function ($echo) {
        echo $echo;
   }
];

If you want to store a function that has already been declared then you can simply refer to it by name as a string:

function do_echo($echo) {
    echo $echo;
}

$functions = [
  'function1' => 'do_echo'
];

In ancient versions of PHP (<5.3) anonymous functions are not supported and you may need to resort to using create_function (deprecated since PHP 7.2):

$functions = array(
  'function1' => create_function('$echo', 'echo $echo;')
);

All of these methods are listed in the documentation under the callable pseudo-type.

Whichever you choose, the function can either be called directly (PHP ≥5.4) or with call_user_func/call_user_func_array:

$functions['function1']('Hello world!');

call_user_func($functions['function1'], 'Hello world!');

Leave a Comment