PHP: Define function with variable parameter count?

JD Isaacks picture JD Isaacks · Jan 22, 2010 · Viewed 13.8k times · Source

Is there a way to define a function in PHP that lets you define a variable amount of parameters?

in the language I am more familiar with it is like so:

function myFunction(...rest){ /* rest == array of params */ return rest.length; }

myFunction("foo","bar"); // returns 2;

Thanks!

Answer

John Conde picture John Conde · Jan 22, 2010

Yes. Use func_num_args() and func_get_arg() to get the arguments:

<?php
  function dynamic_args() {
      echo "Number of arguments: " . func_num_args() . "<br />";
      for($i = 0 ; $i < func_num_args(); $i++) {
          echo "Argument $i = " . func_get_arg($i) . "<br />";
      }
  }

  dynamic_args("a", "b", "c", "d", "e");
?>

In PHP 5.6+ you can now use variadic functions:

<?php
  function dynamic_args(...$args) {
      echo "Number of arguments: " . count($args) . "<br />";
      foreach ($args as $arg) {
          echo $arg . "<br />";
      }
  }

  dynamic_args("a", "b", "c", "d", "e");
?>