Write a program which includes a function sum. This function sum should be designed to add an arbitrary list of parameters. (For e.g., if you call the function sum() as sum (1, 2) it should return the result 3 and if again you call the function sum() as sum(1,3,4) it should return the result 8
CodePudding user response:
You can use func_get_args
and do a foreach
on the arguments, summing them and returning the value.
function sum()
{
$arg_list = func_get_args();
$total = 0;
for ($i = 0; $i < count($arg_list); $i ) {
$total = $arg_list[$i];
}
return $total;
}
CodePudding user response:
This is a variable length parameter.