Accept Unlimited Arguments in a PHP Function

Quick Summary
- Put three dots before a parameter name to make it variadic, and PHP collects every argument in that position into an array.
- The example sums integers with int ...$numbers; the dots need PHP 5.6 and the int types need PHP 7 or later.
- The variadic parameter must come last, and an existing array can be unpacked into the call with the same three dots.
A variadic parameter lets a PHP function accept unlimited arguments. You write it with three dots before the parameter name, and PHP collects all the values passed in that position into an array. The ... syntax has been around since PHP 5.6; the int type declarations in this example need PHP 7 or later.
<?php
function sum( int ...$numbers ):int {
$result = 0;
for($i=0;$i<count($numbers);$i++){
$result += $numbers[$i];
}
return $result;
}
echo sum(3,4,3,10);
echo PHP_EOL;
echo sum(3,4,3,10,4);How it works
int ...$numbersgathers every argument into the array$numbers, andintrequires each of them to be an integer.- The
forloop adds up the values, and:intdeclares that the function returns an integer. sum(3,4,3,10)returns 20 andsum(3,4,3,10,4)returns 24.PHP_EOLprints a line break between the two results.- Called with no arguments,
sum()returns 0, because the array is empty.
Good to know
- The variadic parameter must be the last one. You can put regular parameters before it, for example
function sum( $label, int ...$numbers ). - If your numbers are already in an array, unpack it into the call with the same three dots:
sum( ...$values ). array_sum( $numbers )gives the same total as the loop in a single call.
Related articles
- default values for function parameters: make regular parameters optional

