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);
}
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.
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.
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.
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.
No. That's what call_user_func_array()
is for.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With