PHP Reference ยท Functions and Classes
Variadic functions in PHP
Reference for PHP variadic functions: the ...$args parameter, typed variadics, unpacking arrays with the spread operator, named arguments and func_get_args().
A variadic function accepts any number of arguments. You declare it by putting ... before the last parameter; PHP collects all the extra arguments into an array under that name. The same three dots at a call site do the opposite: they unpack an array or Traversable into separate arguments.
Variadics replace the older func_get_args() approach with something that is typed, documented in the signature and visible to static analysis.
function total(int ...$numbers): int { return array_sum($numbers); } echo total(1, 2, 3); // 6 echo total(...[4, 5, 6]); // 15
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
function name(Type ...$args): ReturnType call(...$arrayOrTraversable);
| Part | Description |
|---|---|
...$args |
Must be the last parameter. Receives all remaining arguments as a list. |
Type ...$args |
Every collected argument must match Type. |
&...$args |
Collects by reference. |
f(...$x) |
Unpacks $x into arguments. String keys become named arguments (PHP 8.1+). |
Return value: the function returns whatever its body returns; $args is a list array (or has string keys for named extras).
Errors: a collected argument of the wrong type throws TypeError; unpacking something that is not an array or Traversable throws Error.
Usage notes
- Only one variadic, and it must be last. It cannot have a default value; with no extra arguments it is an empty array.
- Extra named arguments (
options('a', color: 'red')) end up in$restwith string keys, sojson_encodeshows an object. - Unpacking order. You can combine fixed arguments and several unpackings:
f(1, ...$a, ...$b). Positional unpacking after a named argument is an error. - Duplicates. When an unpacked string key names a parameter that was already given, PHP throws an
Error. func_get_args()still works in any function and returns every argument, including undeclared extras, but has no types. Prefer a variadic parameter in new code. Seefunc_get_args().- Spread in arrays.
[...$a, ...$b]merges arrays; string keys are allowed since PHP 8.1. See the spread operator. - Performance. Collecting arguments allocates an array; fine for normal use, but avoid it in the hottest loops.
- Overriding. A child method may add variadics but must remain compatible with the parent signature.