30

Apologies for the newbie question but i have a function that takes two parameters one is an array one is a variable function createList($array, $var) {}. I have another function which calls createList with only one parameter, the $var, doSomething($var); it does not contain a local copy of the array. How can I just pass in one parameter to a function which expects two in PHP?

attempt at solution :

function createList (array $args = array()) {
    //how do i define the array without iterating through it?
 $args += $array; 
 $args += $var;


}
0

3 Answers 3

60

If you can get your hands on PHP 5.6+, there's a new syntax for variable arguments: the ellipsis keyword.
It simply converts all the arguments to an array.

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}
echo sum(1, 2, 3, 4);

Doc: ... in PHP 5.6+

Sign up to request clarification or add additional context in comments.

1 Comment

It's also worth noting that this is advantageous because you can now type hint a variable number of arguments, as the accepted answer mentions that is a huge downside of func_get_args()
22

You have a couple of options here.

First is to use optional parameters.

  function myFunction($needThis, $needThisToo, $optional=null) {
    /** do something cool **/
  }

The other way is just to avoid naming any parameters (this method is not preferred because editors can't hint at anything and there is no documentation in the method signature).

 function myFunction() {
      $args = func_get_args();

      /** now you can access these as $args[0], $args[1] **/
 }

1 Comment

Awesome did not know you can set a parameter to null thanks!
4

You can specify no parameters in your function declaration, then use PHP's func_get_arg or func_get_args to get the arguments.

function createList() {
   $arg1 = func_get_arg(0);
   //Do some type checking to see which argument it is.
   //check if there is another argument with func_num_args.
   //Do something with the second arg.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.