How to pass variable number of arguments to a PHP function

Viewed 119742

I have a PHP function that takes a variable number of arguments (using func_num_args() and func_get_args()), but the number of arguments I want to pass the function depends on the length of an array. Is there a way to call a PHP function with a variable number of arguments?

10 Answers

I wondered, I couldn't find documentation about the possiblity of using named arguments (since PHP 8) in combination with variable arguments. Because I tried this piece of code and I was surprised, that it actually worked:

function myFunc(...$args) {
    foreach ($args as $key => $arg) {
        echo "Key: $key Arg: $arg <br>";
    }
}
echo myFunc(arg1:"foo", arg2:"bar");

Output:

Key: arg1 Arg: foo
Key: arg2 Arg: bar

In my opinion, this is pretty cool.

Related