Posts tagged ‘function’

Unlimited PHP Function Parameters

If you’ve ever used PHP’s library functions you’ve most likely noticed that several function such as array() can take an indeterminate number of arguments. Normally when defining a function you specify each argument in the function declaration. Obviously it would be impossible to define an infinite number of arguments in such a way. PHP does, however, allow you to accomplish this through the function func_get_args().

func_get_args() returns an array consisting of all of the arguments passed to a function. Using this method you can bypass the conventional method of defining parameters in the function definition all-together. Here is an example:

function add()
{
	$total = 0;
	$args = func_get_args();

	foreach($args as $arg)
	{
		if(is_numeric($arg))
			$total += $arg;
	}
	return $total;
}

echo add(1, 2, 3); //will return 6

If for whatever reason you need to know the total number of arguments passed to a function, PHP provides the func_num_args() function.

When retrieving arguments in this manner it is important to remember that func_get_args only returns an array of arguments passed by the user. It does not account for default values.