Coder Perfect

In PHP, an Array, not an Array, is passed as an argument.


I seem to recall that in PHP, you may give an array as a list of arguments to a function by dereferencing it in the conventional func($arg1, $arg2) fashion. But now I’m at a loss as to how to proceed. I remember how to pass by reference and how to “glob” receiving parameters… but not how to de-list the array and convert it to a list of arguments.

It may be as simple as func(&$myArgs), but I’m not convinced that’s the case. Unfortunately, the manual hasn’t revealed anything yet. For the past year or two, I haven’t needed to use this particular feature.

Asked by Robert K

Solution #1


Answered by vartec

Solution #2

As previously stated, starting with PHP 5.6+, you can (and should!) call a function with an array of parameters using the… token (aka “splat operator,” part of the variadic functions functionality):

function variadic($arg1, $arg2)
    // Do stuff
    echo $arg1.' '.$arg2;

$array = ['Hello', 'World'];

// 'Splat' the $array in the function call

// 'Hello World'

The position of array items in the array, not their keys, is used to map them to arguments.

According to CarlosCarucce’s comment, in all circumstances, this approach of argument unpacking is by far the fastest. It’s over 5x faster than call user func array in some tests.

Because I think it’s a good idea (though it’s not directly linked to the query), you can type-hint the splat operator parameter in your function definition to ensure that all of the passed values are of the same type.

(Just keep in mind that this must be the last argument you define, and it will bundle all parameters supplied to the function into the array.)

This is useful for ensuring that an array contains only elements of a certain type:


// Define the function...

function variadic($var, SomeClass ...$items)
    // $items will be an array of objects of type `SomeClass`

// Then you can call...

variadic('Hello', new SomeClass, new SomeClass);

// or even splat both ways

$items = [
    new SomeClass,
    new SomeClass,

variadic('Hello', ...$items);

Answered by simonhamp

Solution #3

You must also pass the function as: if you want to apply an instance method on an array.

call_user_func_array(array($instance, "MethodName"), $myArgs);

Answered by Jeff Ober

Solution #4

For completeness’ sake, this also works as of PHP 5.1:

function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"


Instead of using ReflectionMethod::invokeArgs, you should use ReflectionMethod::invokeArgs and supply the object as the first parameter.

Answered by DanMan

Post is based on