Variable length argument lists for functions in PHP

Variable length argument lists for functions in PHP

Ever found yourself needing a function that can take an arbitrary number of arguments? Luckily it's pretty easy to do in PHP (as of 5.6) with something called a variadic function.

[Pre 5.6 you would need to rely on using func_get_args()]

PHP's sprintf function is a great example of a function that benefits from this. We all know this function takes a format string with directives, and a variable number of conversion values to be applied onto the format string. This is the function signature in its variadic function form:

function sprintf(string $format, ...$values): string {}

The key here is the second parameter ...$values . The ... (sometimes referred to as a splat or scatter operator) indicates it will accept any number of parameters, after the 'normal' $format parameter, and present them as an array called $values that can be accessed just as you would any other array.

If we wanted to build our own function, for say taking a url and adding in a list of ids, we could do something like the following:

public function buildPath(string $basePath, ...$ids): string
{
    foreach ($ids as $id) {
        // do some checks here
    }

    return sprintf($basePath, ...array_map('urlencode', $ids));
}

Here we can see that we can iterate over the $ids as they are an array, and perform any work we want to against them.  You could then call this function like this:

$this->buildPath('/api/customer/%s/bookings/%s', $cId, $bId);

You might notice the second use of the ...; as well as its use in a variadic function, it can also be used for argument unpacking.  In this case, after an array is returned from the array_map call, it will unpack it into a list of function arguments, which we already know sprintf accepts!

And it's as simple as that, the hardest part is remembering it's called a variadic function!