How to use variable-length parameter lists

A function that adds a list of numbers

      function add() {
        $numbers = func_get_args(); 
        $total = 0; 
        foreach($numbers as $number) { 
          $total += $number; 
        } return $total; 
      } $sum = add(5, 10, 15); // $sum is 30
      

A function that averages one or more numbers

      function average($x) { // $x is here to force at least one argument
        $count = func_num_args(); 
        $total = 0; 
        for ($i = 0; $i < $count; $i++) { 
          $total += func_get_arg($i); 
        } 
        return $total / $count;
      }
      $avg = average(75, 95, 100); // $avg is 90
      

Using required parameters with a variable parameter list

      function array_append(&$array, $x) {
        $values = func_get_args();
        array_shift($values); 
        foreach($values as $value) { 
          $array[] = $value;
        } 
      } 
      $data = array('apples', 'oranges'); 
      array_append($data, 'grapes', 'pears');
      

Back