26 September 2006
Variable Numbers of Arguments in PHP
There is a problem which infrequently appears in nearly every programming language: calling a function with a variable number of arguments. It is interesting from both sides of development: if you’re writing a function, how will you collect variable numbers of arguments? If you’re consuming a function, how will you provide the arguments?
Much of the problem stems from the lack of a “standard” way to do it. You can collect and pass all arguments in an array. You can explicitly list every possble argument with a default value. You can list primary arguments explicitly and collect an array as the final argument which specifies the rest of the arguments. But each of these solutions is really a work around. What you’re probably looking for is something like C’s ... argument.
As it happens, PHP does have a functional equivelent to C’s ... token. PHP provides three functions in the func_ group: func_num_args, func_get_arg and func_get_args. Each of these operates on all the arguments, not just the unnamed ones. Unlike C, each of these functions just works- you don’t need to call va_start or do any initialization.
func_num_args()- Returns a zero-based count of how many arguments the function recieved.func_get_arg($index)- Returns element in the function’s argument array at index $index. This is not an associative array internally, so you must use integer indices.func_get_args()- Returns the whole of the internal argument list as an array.
There really aren’t many uses for this. In most cases of reasonable complexity, there is a better way to handle problems which appear to require variable argument lists. Many cases can be solved with a specialized class. Others simply don’t need that level of flexibility. In the case that a problem really does require variable arguments, these three functions provide the best way to handle it.

