0

I need to call a function as such:

function something($argument1, $argument2, $data)

where $data can be any amount of variables comma separated: 1,2,3,4

so for instance I would call:

function something ('blue', 'green', 1,2,3)

or

function something ('red', 'black', 1,2,3,4,5,6,7,8,9)

I have looked into the ellipsis keyword (...) but I cannot see how I can implement this with my 2 static arguments ($argument1 and $argument2).

My intuition would be to put the comma separated into an array before calling the function and sending the array to the function?

Thanks!

Blaise
  • 143
  • 1
  • 1
  • 9
  • Possible duplicate of [Is it possible to send a variable number of arguments to a JavaScript function?](http://stackoverflow.com/questions/1959040/is-it-possible-to-send-a-variable-number-of-arguments-to-a-javascript-function) – Madhawa Priyashantha Nov 20 '16 at 17:42
  • You can certainly hand over a "stuff" array as a third argument. Or you use the approach of functions with a variable argument number. That allows to indeed use any number of arguments, so you have to implement your own means to make sure those two mandatory arguments are indeed handed over. – arkascha Nov 20 '16 at 17:44
  • For an unknown amount of parameters being passed to a function, use an array. – Kitson88 Nov 20 '16 at 17:46

3 Answers3

1

i don't know exactly what you are trying to do but, if you want a function with lots of arguments and since you know that the first 2 argument is fixed, you can use php func_get_args() to get the arguments passed to the function.

Canaan Etai
  • 3,455
  • 2
  • 21
  • 17
0

You can include required arguments before using the splat operator. All arguments captured by the splat operator will be available in an array. For example,

function splat_example($arg_1, $arg_2, ...$data_list) {
   echo $arg_1 . "\r\n";
   echo $arg_2 . "\r\n";
   foreach ($data_list as $data) {
       echo $data . "\r\n";
   }
}

So the following,

splat_example('red', 'blue', 1, 2, 3, 4); 

would result in,

red
blue
1
2
3
4

See it working here http://sandbox.onlinephpfunctions.com/code/36d991aeb4321faf8400d0f6fb017efc50ebe567

Steve
  • 1,853
  • 16
  • 30
0

you can pass third parameter as a comma separated string. and then you can convert into array using explode with comma.

function something ('blue', 'green', '1,2,3'){

}

Manraj
  • 205
  • 1
  • 3
  • 10
  • Might as well just pass an array in that case, replace `'1,2,3'` with `[1,2,3]`, saves using `explode()`. – Steve Nov 20 '16 at 18:24