Nasrul Hazim Bin Mohamad

PHP – Using an Arbitrary Number of Parameters

Jan
26

A useful approach to use when you need only one function, but various number of parameters – further workflow might be different for different number of parameter passed to the function.

function arbitrary_function()
{
	$num_of_parameters = func_num_args();
	// if one parameter, do something
	// else if two parameter, do something
	// else, do something else
	return 'Number of parameters: ' . $num_of_parameters;
}

echo '<p>' . arbitrary_function(1) . '</p>'; // Number of parameters: 1
echo '<p>' . arbitrary_function(1,1) . '</p>'; // Number of parameters: 2
echo '<p>' . arbitrary_function(1,1,1,1,1) . '</p>'; // Number of parameters: 5
echo '<p>' . arbitrary_function(1,1,1) . '</p>'; // Number of parameters: 3

Leave a Reply

Your email address will not be published. Required fields are marked *

one × 1 =