23

I've got a varargs type method defined in PHP 7

function selectAll(string $sql, ...$params) { }

The problem I'm running into is that sometimes I want to call this method when I already have an array, and I can't just directly pass an array variable to this method.

Gargoyle
  • 9,590
  • 16
  • 80
  • 145

1 Answers1

35

Use splat operator to unpack the array arguments just like you used in the function:

selectAll($str, ...$arr);

So like this:

function selectAll(string $sql, ...$params) { 
    print_r(func_get_args());
}

$str = "This is a string";
$arr = ["First Element", "Second Element", 3];

selectAll($str, ...$arr);

Prints:

Array
(
    [0] => This is a string
    [1] => First Element
    [2] => Second Element
    [3] => 3
)

Eval for this.


If you don't use splat operator in arguments, you will end up like this

Thamilhan
  • 13,040
  • 5
  • 37
  • 59