Sometimes you do not know how many arguments a function will receive. A variadic function collects them all into an array. You write three dots before the parameter.
<?php
function sum(int ...$numbers): int
{
return array_sum($numbers);
}
echo sum(1, 2, 3) . "\n";
echo sum(10, 20, 30, 40) . "\n";
echo sum();
6
100
0
Inside the function, $numbers is a normal array of the values.
Typed variadics
The type applies to every item. int ...$numbers accepts only integers.
Required first, extras after
A variadic parameter must be last. Put the required ones before it.
<?php
function logMessage(string $level, string ...$parts): string
{
return "[$level] " . implode(" ", $parts);
}
echo logMessage("INFO", "User", "logged", "in");
[INFO] User logged in
Spreading an array into arguments
The same three dots work in a call. They unpack an array into separate arguments.
<?php
function add(int $a, int $b, int $c): int
{
return $a + $b + $c;
}
$values = [1, 2, 3];
echo add(...$values);
6
Merge arrays with the spread operator
<?php
$first = ["a", "b"];
$second = ["c", "d"];
print_r([...$first, ...$second]);
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
String keys become named arguments
Since PHP 8.1, an array with string keys can be spread into named arguments.
<?php
function createUser(string $name, int $age): string
{
return "$name is $age";
}
$data = ["age" => 30, "name" => "Ravi"];
echo createUser(...$data);
Ravi is 30
The old way: func_get_args()
Before variadic parameters, code used func_get_args() inside the function. You may see it in older projects.
<?php
function oldSum()
{
return array_sum(func_get_args());
}
echo oldSum(1, 2, 3);
6
Use ...$args in new code. It is clearer and supports types.
A real use
printf(), max() and array_merge() are all variadic. When you write a helper that “takes some values”, a variadic is usually the right shape.