Tips & Tricks

14

Aug 09

Expand an array into function arguments with call_user_func_array

call_user_func_array is a time saving, though not commonly used function that allows you to treat the items of an array as arguments when calling a function. You indicate which function call_user_func_array is to call with the first argument, which can take two or three forms, depending on whether you’re using a version of PHP greater or equal to 5.3.

In it’s first form, you supply a function name as the first argument.

function sum(x, y, z) {
    return x + y + z;
} 
 
$arr = array(1, 3, 5);
echo call_user_func_array('sum', $arr);    // prints 9

In the second form, you pass an array containing an object reference and the name of a method as the first argument. The following would call $obj->sum.

echo call_user_func_array(array($obj, 'sum'), $arr);

The third form involves the use of a lambda, and so it only works with versions of PHP >= 5.3. In this form you simply define the lambda, and use its reference as the first parameter.

$func = function(x, y, z) {
    return x + y + z;
}
$arr = array(5, 2, 7);
echo call_user_func_array($func, $arr);    // prints 14