php - How to handle undetermined number of arguments?

I have a procedure which works like this:
$e = "name,Alan,Georges,Edith,Julia,Donna,Bernard,Christophe,Salvatore,Laure,Thomas";
$f = explode("," ,$e);
if (function_exists($f[0])) {
$f[0]($f[1], $f[2], $f[3], $f[4], $f[5], $f[6], $f[7], $f[8], $f[9], $f[10]);
}
Can I handle this more elegantly? I mean, can I handle for example 30 parameters without writing :
$f[0]($f[1], $f[2], $f[3], ..., ..., $f[26], $f[27], $f[28], $f[29], $f[30]);
Answer
Solution:
You can usecall_user_func_array()
to pass parameters via array:
$f = ['foo', 'param1', 'param2'];
$func = array_shift($f); // remove function name.
call_user_func_array($func, $f);
(use the above example code with the function below...)
To obtain an arbitrary list of function arguments, usefunc_get_args()
function foo() {
$args = func_get_args();
print_r($args);
}
You'd not even have to specifiy the arguments, just pass as many as you want:
foo(1, 2, 4, 'hello', 1.234, ['foo', 'bar']);
Produces the output
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => hello
[4] => 1.234
[5] => Array
(
[0] => foo
[1] => bar
)
)
https://www.php.net/manual/en/function.func-get-args
https://www.php.net/manual/en/function.call-user-func-array
Hope that helps
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: deprecated: directive 'allow_url_include' is deprecated in unknown on line 0
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.