25

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.

1 Answer 1

37

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

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

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.