Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlimited arguments for PHP function? [duplicate]

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 something like

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

but the anotherFunc would receive them as if it was called using anotherFunc($p1, $p2, $p3, $p4, $p5...)

like image 936
Hailwood Avatar asked Feb 15 '11 20:02

Hailwood


People also ask

Can a function take unlimited arguments?

We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.

How many maximum arguments can be returned?

Answer 1: When it comes to passing arguments to function, the maximum number of arguments that is possible to pass is 253 for a single function of the C++ programming language.

Which PHP function accepts number of parameters?

Which of the following PHP functions accepts any number of parameters? Explanation: func_get_args() returns an array of arguments provided. One can use func_get_args() inside the function to parse any number of passed parameters.

What is $params in PHP?

PHP Parameterized functions They are declared inside the brackets, after the function name. A parameter is a value you pass to a function or strategy. It can be a few value put away in a variable, or a literal value you pass on the fly. They are moreover known as arguments.


3 Answers

call_user_func_array('anotherFunc', func_get_args());

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

like image 97
mfonda Avatar answered Sep 28 '22 08:09

mfonda


Previously you should have used func_get_args(), but in a 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 you will pass.

like image 35
Salvador Dali Avatar answered Sep 28 '22 08:09

Salvador Dali


Is there a reason why you couldn't use 1 function argument and pass all the info through as an array?

like image 35
Stoosh Avatar answered Sep 28 '22 07:09

Stoosh