Passing an array to varargs in php

I have a method like varargs defined in PHP 7

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

The problem I am facing is that sometimes I want to call this method when I already have an array and I cannot just pass the array to a variable for this method.

+4
source share
1 answer

Use the splat operator to decompress array arguments in the same way as you used in a 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);

Print

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

Eval for this.


If you do not use the splat operator in the arguments, you will get like this

+6
source

Source: https://habr.com/ru/post/1668085/


All Articles