Passing Variable Parameters to a function
How to pass variable parameters to a function?
For example - define a generic function genAdd which will add all the parameters we passing.
$i = genadd(2,5);
$j = genadd(3,5,8);
So result of $i should be 7 and $j should be 16.
Fortunately PHP has following functions to achieve this.
func_get_args(); — This function will return array of argument list
func_get_arg(int arg_num); — This function will return an item from argument list.
func_num_args(); — This function will return number of arguments passed to a function
Implemetation
function genAdd(){
$sum = 0;
$args = func_get_args();
for($i = 0; $i < func_num_args(); $i++){
$sum += $args[$i];
}
return $sum;
}
$sum = genAdd(1,2,3);
echo $sum;
echo “<br>”;
$sum = genAdd(1,2,3,10,1);
echo $sum;
