Splat!

While looking through the Query Builder class in the Laravel source code today, I came across something I hadn’t seen before in PHP:

$query->{$method}(…array_values($value));

I had no idea what the three dots meant, so I went looking for it. Turns out it’s a feature added in PHP 5.6 called “variadic functions”, and is often referred to as the “splat operator”, or “scatter operator”. The page I found was from Lorna Jane, and explained it well. Basically, it lets you pack as many parameters as you want to pass in to a function into a single array. Here’s an example:

function test(...$arr)
{
    var_dump($arr);
}

test("value 1", "value 2");

Output:

array(2) {
  [0]=>
  string(7) "value 1"
  [1]=>
  string(7) "value 2"
}

If you remove the three dots, you get this:

function test($arr)
{
    var_dump($arr);
}

test("value 1", "value 2");

Output:
string(7) "value 1"

But wait! There’s more!

Turns out this triple dot thing can work both ways. It can also turn an array into individual parameters, like this:

function test($arg1, $arg2, $arg3)
{
    var_dump($arg1,$arg2,$arg3);
}

$arr[] = "value 1";
$arr[] = "value 2";
$arr[] = "value 3";

test(...$arr);

Outputs:

string(7) "value 1"
string(7) "value 2"
string(7) "value 3"

This usage is called Argument Unpacking. Here’s what happens if you don’t put the three dots:

function test($arg1, $arg2, $arg3)
{
    var_dump($arg1,$arg2,$arg3);
}

$arr[] = "value 1";
$arr[] = "value 2";
$arr[] = "value 3";

test($arr);

Outputs:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(), 1 passed in Standard input code on line 22 and exactly 3 expected in Standard input code:13
Stack trace:
#0 Standard input code(22): test(Array)
#1 {main}
  thrown in Standard input code on line 13

This shows that it is in fact unpacking that array into the individual input variables for the test function.

Thanks Lorna Jane for the great explanation!

Leave a Reply

Your email address will not be published. Required fields are marked *