Main Content

Passing a variable number of parameters in to a function / method

Archive - Originally posted on "The Horse's Mouth" - 2010-08-20 23:11:29 - Graham Ellis

How many columns are there in each row in a table? It will vary, depending on the table!

If I want to write a "row" function in PHP, passing in as parameters each of my columns, I don't know the parameter count. But I can find out using the fun_num_args function, and I can then get each of them using the func_get_arg function.

Here's an example:
  function row() {
    $res = "<tr>";
    for ($k=0; $k<func_num_args(); $k++) {
      $res .= func_get_arg($k);
    }
    $res .= "</tr>";
    return $res;
  }


In Python, you can collect a variable number of arguments using a * in the def of the function / method, such as
  def row(*eachcol):
and indeed you could collect named arguments into a dictionary using **.

In Perl, you can check how many arguments you have using $#_, or using @_ in a scalar content

And in Tcl, a final argument called args in a proc definition will "sponge up" all remaining parameters, no matter how many of them there are.
  proc ceiling {limit args} {

One slight word of caution - it's often much better to pass an array or a list into a function than a variable number of arguments. But if you do need to pass them individually, then the tips above will point you in the right direction for Perl, PHP, Python and Tcl.