Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you implode an array into function arguments?

Tags:

arrays

php

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);
}
like image 947
JREAM Avatar asked Apr 22 '12 21:04

JREAM


People also ask

Can an array be used as an argument to a function?

Single array elements can also be passed as arguments. This can be done in exactly the same way as we pass variables to a function.

How do you implode an array?

The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function. If we have an array of elements, we can use the implode() function to join them all to form one string.

What are the uses of explode () and implode () functions?

PHP implode() and explode() The implode() function takes an array, joins it with the given string, and returns the joined string. The explode() function takes a string, splits it by specified string, and returns an array.

What is implode function?

The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional.


2 Answers

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

like image 83
Ignacio Vazquez-Abrams Avatar answered Sep 27 '22 23:09

Ignacio Vazquez-Abrams


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);
like image 36
Beat Avatar answered Sep 27 '22 22:09

Beat