JREAM
JREAM

Reputation: 5931

Can you implode an array into function arguments?

Is it possible to have an array and pass it into a function as separate arguments?

$name = array('test', 'dog', 'cat');
$name = implode(',' $name);
randomThing($name);

function randomThing($args) {
    $args = func_get_args();
    // Would be 'test', 'dog', 'cat'

    print_r($args);
}

Upvotes: 8

Views: 7339

Answers (2)

Beat
Beat

Reputation: 1380

As of PHP 5.6 you can use ... to pass an array as function arguments. See this example from the PHP documentation:

function add($a, $b) {
    return $a + $b;
}

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);

Upvotes: 9

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798716

No. That's what call_user_func_array() is for.

Upvotes: 12

Related Questions