Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Define function with variable parameter count? [duplicate]

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!

like image 811
JD Isaacks Avatar asked Jan 22 '10 14:01

JD Isaacks


2 Answers

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");
?>
like image 157
John Conde Avatar answered Oct 21 '22 12:10

John Conde


You can accept a variable number of arguments to any function, so long as there are enough to populate all the declared arguments.

<?php

function test ($a, $b) { }

test(3); // error
test(4, 5); // ok
test(6,7,8,9) // ok

?>

To access the extra un-named arguments passed to test(), you use the functions func_get_args(), func_num_args(), and func_get_arg($i) :

<?php

// Requires at least one param, $arg1
function test($arg1) {

  // func_get_args() returns all arguments passed, in order.
  $args = func_get_args();

  // func_num_args() returns the number of arguments
  assert(count($args) == func_num_args());

  // func_get_arg($n) returns the n'th argument, and the arguments returned by
  // these functions always include those named explicitly, $arg1 in this case
  assert(func_get_arg(0) == $arg1);

  echo func_num_args(), "\n";
  echo implode(" & ", $args), "\n";

}

test(1,2,3); // echo "1 & 2 & 3"

?>
like image 31
meagar Avatar answered Oct 21 '22 12:10

meagar