Can a PHP function accept an unlimited number of parameters? [duplicate] Can a PHP function accept an unlimited number of parameters? [duplicate] php php

Can a PHP function accept an unlimited number of parameters? [duplicate]


In PHP, use the function func_get_args to get all passed arguments.

<?phpfunction myfunc(){    $args = func_get_args();    foreach ($args as $arg)      echo $arg."/n";}myfunc('hello', 'world', '.');?>

An alternative is to pass an array of variables to your function, so you don't have to work with things like $arg[2]; and instead can use $args['myvar']; or rewmember what order things are passed in. It is also infinitely expandable which means you can add new variables later without having to change what you've already coded.

<?phpfunction myfunc($args){    while(list($var, $value)=each($args))      echo $var.' '.$value."/n";}myfunc(array('first'=>'hello', 'second'=>'world', '.'));?>


You can use these functions from within your function scope:

  • func_get_arg()
  • func_get_args()
  • func_num_args()

Some examples:

foreach (func_get_args() as $arg){    // ...}

for ($i = 0, $total = func_num_args(); $i < $total; $i++){    $arg = func_get_arg($i);}


if you have PHP 5.6+ , then you can use

function sum(...$numbers) 

functions.variable-arg-list