Development

The Splat Operator in PHP

Since PHP version 5.6, we have been able to use the splat or spread operator. It goes by many names, but those three dots offer some really powerful features. If you've ever used variadic functions or argument unpacking, you'll know what I mean.

Variadic Functions

The splat operator allows you to accept a mutable number of arguments for your functions. Take the example below. You could pass any number of names to the welcome function, and it would output a greeting for each of them.

function welcome($greeting, ...$names) {
   foreach ($names as $name) {
      echo "{$greeting}, {$name}\n";
   }
}

welcome("Hello", "Grant", "James", "David");

You're probably thinking, well I could just pass an array, no? Yes, you could, but that would make passing just one attribute pretty ugly. With variadic functions, your API remains clean whether you send 1 or 20 attributes.

public function addRecipients(...$recipients) {
   $this->recipients = $recipients;
}

addRecipients('name@email.com');

addRecipients(
   'name@email.com',
   'name@email2.com'
);

Thanks to PHP 8 and its named arguments, variadic functions can be even more powerful, check this out.

function addCar(...$properties) {
   print_r($properties);
}

addCar(
   manufacturer: 'BMW',
   model: 'M3'
);

// Array ( [manufacturer] => BMW [model] => M3 )

Argument Unpacking

Argument unpacking is used in the function call, rather than inside the function's list of expected parameters. It allows you to pass arrays into a function that would typically expect separate parameters.

function sum($a, $b, $c) {
    return $a + $b + $c;
}

$numbers = [3, 2];
echo sum(5, ...$numbers);

Once again, PHP's named arguments shows how useful this could be in your code. Unpacking an associative array onto a function that requires multiple parameters.

function createUser($name, $age, $gender) {
   print_r([$gender, $age, $name]);
}

$profile = [
    'name' => 'Grant',
    'age' => '25',
    'gender' => 'male'
];
createUser(...$profile);

// Array ( [0] => male [1] => 25 [2] => Grant )

Usage in Arrays

Since PHP 7.4 we have been able to use the splat operator inside arrays. In its simplest form, you can see it's possible to 'embed' one array into another.

You can also do much more, such as unpacking the output of a function into an array. I highly recommend checking out the proposal for an example of what's possible.

$names1 = ["Grant", "Ben"];
$names2 = [...$names1, "James", "David"];
print_r($names2);

// (
//   [0] => Grant
//   [1] => Ben
//   [2] => James
//   [3] => David
// )