PHP function with variable arguments

PHP Best Practices

Best Practice for passing a variable list of arguments to a function for processing.


Date : 2006-02-15
There are many different reasons why we may want to pass a variable list of arguments to a function. One of the simplest examples to demonstrate would be a function to concatenate a group of strings. Here is an example of how that is done:

Code:
<?php
  function concatenate() {
    $result = "";
    for ($i = 0;$i < func_num_args();$i++) {
      $result .= func_get_arg($i) . " ";
    }
    return $result;
  }
  echo concatenate("eenie","meenie","minie","mo");
?>


Notice the use of func_num_args to determine how many arguments were passed and func_get_args to retrieve those values.

Once you have the concept of this function you can apply this to any number of functions. For instance you could write a function to create a query searching for a variable number of search words. You can also make it reference specific arguments statically and the rest dynamicaly. For instance you could adjust the above function to have a different character or string entered in between each argument by placing that argument at the beginning (or end) of the argument list like this:

Code:
<?php
  function concatenate() {
    $result = "";
    if (func_num_args() > 1) {
      $delimiter = func_get_arg(0);
      $result = func_get_arg(1);
      for ($i = 2;$i < func_num_args();$i++) {
        $result .= $delimiter . func_get_arg($i);
      }
      return $result;
    } else {
      return "";
    }
  }
  echo concatenate(",","eenie","meenie","minie","mo");
?>


Now you should start to see the options open up to you. Tell us what new and interesting applications you have found for this method.

Comments :

No comments yet
  • Search For Articles