Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing multiple arguments to function php

Tags:

function

php

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;


}
like image 217
Undermine2k Avatar asked Sep 04 '25 17:09

Undermine2k


2 Answers

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+

like image 83
Petruza Avatar answered Sep 07 '25 07:09

Petruza


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] **/
 }
like image 31
Orangepill Avatar answered Sep 07 '25 05:09

Orangepill