Content:
The PHP splat operator, internally known as T_ELLIPSES, is a fairly uncommon yet incredibly useful operator. Introduced in PHP 5.6 back in 2014, the splat operator is denoted with an ellipses (...
). It’s also sometimes known as the spread operator.
Its main functions relate to argument/value unpacking, a feature which is common in other programming languages.
There are a few ways to use this operator, which we’ll take a look at below.
Variadic Functions
The splat operator can be used to simplify variadic functions. These are functions which accept a variable number of arguments.
function sum(...$numbers)
{
$total = 0;
foreach ($numbers as $number) {
$total += $number;
}
return $total;
}
echo sum(1, 6, 3, 8, 3, 2, 3) # 26
The variable prefixed with the splat operator will contain an array of the passed variables. Note that this does not include any positional or named arguments appearing before the variadic variable.
function calc(string $operator, ...$numbers) {...}
echo calc('+', 1, 6, 3, 8, 3, 2, 3) # 26
This new function accepts an operator as the first variable. This will not be included in the $numbers
array.
Variadic parameters must be placed at the end of the function definition, as it essentially collects everything left over following the other arguments. It’s also only possible to have one variadic parameter.
While mainly used with arrays, the splat operator can also be used with any Traversable
.
Prior to the splat operator, it was possible to use variable function lists using func_get_args()
. This function, however, returns all arguments, so requires any named arguments to be filtered out. The splat operator is therefore much more convenient.
Array Unpacking
Another function of the splat operator is the ability to unpack arrays and other Traversables
into lists of arguments.
function add(int $num1, int $num2)
{
return $num1 + $num2;
}
$nums = array(4,2);
echo add(...$nums); # 6
In this example, the array containing two values is unpacked into the argument list. Unlike using ...
in the function definition, the unpacked values are handled as separate variables.
If you attempt to unpack more values than the function accepts, the extra values will be ignored.
This can also be used to merge arrays, by unpacking one array into the other.
$fruits = array('apple', 'orange', 'pear');
$foods = array('carrots', ...$fruits, 'beans');
# ['carrots', 'apple', 'orange', 'pear', 'beans']
It’s possible to do this anywhere within the second array.
Conclusion
The splat is a very useful operator in PHP. In particular, it’s a great way to combine arrays, particularly if you need to influence the position of the new values.
While variable-length function parameters have long been possible, the use of the splat operator makes them much more convenient.