Is it possible to have a function in PHP which takes 1 or more numbers and returns their sum ?
In PHP 5.6 and later you will be able to do it this way:
function sum(...$nums) {
for($i=0,$sum=0;$i<count($nums);$i++) {
$sum += $nums[$i];
}
return $sum;
}
Or, simplified using foreach:
function sum(...$nums) {
$sum=0;
foreach($nums as $num) {
$sum += $num;
}
return $sum;
}
Source: PHP Manual: Function arguments
You can make use of the function func_num_args and func_get_arg as:
function sum() {
for($i=0,$sum=0;$i<func_num_args();$i++) {
$sum += func_get_arg($i);
}
return $sum;
}
And call the function as:
echo sum(1); // prints 1
echo sum(1,2); // prints 3
echo sum(1,2,3); // prints 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With