0

Google won't help me; I want to pass an array as an argument list to a function.

I can't edit the function itself, so I can't pass an array. It expects this:

function doSomething($arg1, $arg2, [$arg3...]) {
    //code...
}

And I have this:

$args = array('arg1', 'arg2', 'arg3'...);

How can I pass them anyway?

0

1 Answer 1

1

You can use call_user_func_array.

Use like:

$array = array(1, 2, 3);
call_user_func_array("myfunc", $array);

function myfunc($a, $b, $c) {
    var_dump($a, $b, $c); // 1 2 3
}

$array = array(2, 3);
$first = 1;
call_user_func_array("myfunc", array_merge(arary($first), $array));

function myfunc($a, $b, $c) {
    var_dump($a, $b, $c); // 1 2 3
}

In case of an object instance your callback should look like:

array($obj, "someFunc")

so:

call_user_func_array(array($obj, "someFunc"), $array);
Sign up to request clarification or add additional context in comments.

4 Comments

But how can I do this with the first arg not being in the array?
What do you mean? You can always do some array_merge magic to get the arguments you want.
Hmm, got it - but... "call_user_func_array() expects parameter 1 to be a valid callback, function '' not found or invalid function name" $obj->doSomething not working
See my updated answer. Callbacks on objects are slightly different.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.