Gargoyle
Gargoyle

Reputation: 10324

Pass array to varargs function in php

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.

Upvotes: 25

Views: 11895

Answers (1)

Thamilhan
Thamilhan

Reputation: 13313

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

Upvotes: 37

Related Questions