PHP functions and varying numbers of arguments
Added on: Friday 29th May 2009
There are times when you want to pass an unknown number of arguments to a function. A simple example might be a function to add a list of numbers.
At this point I can hear people shouting - 'to do this you just pass a single parameter that is an array of numbers to add'.
In fact this is what I thought I could do for a bit of code that I needed to add to our content management system but it didn't work.
The problem was that I was using the php function call_user_func_array. This function has two parameters, an array containing the class and function to call and a second array with the function parameters.
I mistakenly thought that the call_user_func_array function would pass the second parameter as an array to the nominated function but it doesn't.
If the function being called has one defined parameter then call_user_func_array passes it the first item in the array and ignores the rest.
There is an easy way around this using the func_num_args and func_get_arg php functions.
In the case of adding a list of numbers the code within the function would be:
for ($i = 0; $i < func_num_args();$i++) {
$return = $return + func_get_arg($i);
}
Just remember not to specify any parameters in the function definition.
Andrew Parrott runs