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
<?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 ...$numbers gathers every argument into the array $numbers, and int requires each of them to be an integer.
  • The for loop adds up the values, and :int declares that the function returns an integer.
  • sum(3,4,3,10) returns 20 and sum(3,4,3,10,4) returns 24. PHP_EOL prints 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.
Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More