Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function take an undefined number of arguments?

Tags:

php

Is it possible to have a function in PHP which takes 1 or more numbers and returns their sum ?

like image 418
user325894 Avatar asked May 03 '10 13:05

user325894


2 Answers

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

like image 196
Leopoldo Sanczyk Avatar answered Sep 23 '22 06:09

Leopoldo Sanczyk


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
like image 32
codaddict Avatar answered Sep 25 '22 06:09

codaddict