How to Use the Splat Operator for Variadic Functions in PHP
In PHP, the splat operator (...), also known as the
ellipsis operator, provides a clean and modern way to declare variadic
functions. Variadic functions are functions that can accept a variable
number of arguments. This article explains how to declare variadic
functions using the splat operator, combine them with normal arguments,
apply type hinting, and unpack arrays into argument lists.
Basic Declaration of a Variadic Function
To declare a variadic function, place the splat operator
(...) directly before the parameter name in the function’s
definition. When the function is called, all arguments passed to that
parameter are automatically collected into an array.
function sumAll(...$numbers) {
$sum = 0;
foreach ($numbers as $number) {
$sum += $number;
}
return $sum;
}
echo sumAll(1, 2, 3, 4); // Outputs: 10In this example, the arguments 1, 2, 3, 4 are grouped
into an array named $numbers inside the function.
Combining Normal and Variadic Arguments
You can mix regular positional arguments with a variadic parameter. However, the variadic parameter must always be the last parameter in the function declaration. Only the arguments that do not match the preceding positional parameters will be collected into the variadic array.
function greetUsers($greeting, ...$names) {
foreach ($names as $name) {
echo "{$greeting}, {$name}!\n";
}
}
greetUsers("Hello", "Alice", "Bob", "Charlie");
// Outputs:
// Hello, Alice!
// Hello, Bob!
// Hello, Charlie!Adding Type Hinting to Variadic Parameters
You can enforce strict data types for variadic arguments by placing the type hint before the splat operator. When a type hint is used, PHP ensures that every argument passed to the variadic parameter matches the specified type.
function concatenateStrings(string ...$strings) {
return implode(" ", $strings);
}
echo concatenateStrings("PHP", "is", "powerful"); // Outputs: PHP is powerful
// This will throw a TypeError in PHP:
// echo concatenateStrings("Age:", 30); Unpacking Arguments Using the Splat Operator
The splat operator also works in reverse. If you already have an
array of data, you can use the ... operator when
calling a function to unpack (or spread) the array
elements into individual arguments.
function introduce($firstName, $lastName) {
return "My name is {$firstName} {$lastName}.";
}
$names = ["John", "Doe"];
// Unpacks the array into $firstName and $lastName
echo introduce(...$names); // Outputs: My name is John Doe.