In addition to call_user_func_array() already mentioned above, since 5.6 you can also perform similar actions via:
Variadic Functions
In which you can pass any number of values to a function, which collects them into an iterable argument:
function foo(...$arguments)
{
foreach ($arguments as $arg) {
echo $arg . PHP_EOL;
}
}
foo(1, 2, 3);
Yields:
1
2
3
This is vaguely similar to passing in an array or call_user_func_array() - albeit more flexible - for instance, you can use typehinting:
function foo(array ...$arguments)
{
//
}
foo([], [], []); // works, each argument is an array
foo(1, 2, 3); // fatal error!
Argument Unpacking
As stated in the release docs Argument Unpacking does the following:
Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator. This is also known as the splat operator in other languages, including Ruby.
This is useful if you already have an array of values that you want to apply to a function with an explicit argument list. This is probably the best approach since it's explicit, and therefore easiest to reason about.
function bar($a, $b, $c)
{
echo $a . PHP_EOL;
echo $b . PHP_EOL;
echo $c . PHP_EOL;
}
$params = [1, 2, 3];
bar(...$params);
Yields:
1
2
3
Otherwise, if you are using <= 5.5, you could approximate the variadic approach with func_get_args():
function baz()
{
foreach (func_get_args() as $arg) {
echo $arg . PHP_EOL;
}
}
baz(1, 2, 3, 4);
PHP functions do not require functions to have explicit argument lists. However, I think it is harder to reason about a function that does not state its arguments explicitly, and it's harder to validate and use the arguments passed into it.
Hope this helps :)
"$var1"is tersely inefficient, you just need the variable:array($var1,$var2,$varN);