Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array to varargs function in php

Tags:

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.

like image 766
Gargoyle Avatar asked Jan 28 '17 06:01

Gargoyle


1 Answers

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

like image 178
Thamilhan Avatar answered Sep 22 '22 05:09

Thamilhan