Unlimited arguments for a PHP function?

In php, how would you create a function that could take an unlimited number of parameters: myFunc($p1, $p2, $p3, $p4, $p5...);

My next question is: how would you pass them into another function similar to

 function myFunc($params){ anotherFunc($params); } 

but anotherFunc will receive them as if it were called using anotherFunc($p1, $p2, $p3, $p4, $p5...)

+8
function php arguments
source share
4 answers
 call_user_func_array('anotherFunc', func_get_args()); 

func_get_args returns an array containing all the arguments passed to the function from which it was called, and call_user_func_array calls the given function, passing it an array of arguments.

+13
source share

You should have used func_get_args() before, but in the new php 5.6 ( currently in beta ) you can use ... operator instead of using.

So, for example, you can write:

 function myFunc(...$el){ var_dump($el); } 

and $el will have all the elements that you will go through.

+4
source share

Is there a reason why you cannot use 1 argument of a function and pass all the information through an array?

+2
source share

Check out the documentation for variable-length argument lists for PHP.

The second part of your question relates to variable functions :

... if parentheses are added to the variable name, PHP will look for the function with the same name as the variable and try to execute it.

0
source share

All Articles