How to Use Variadic Functions in PHP: Syntax and Examples
In PHP, you can create a
variadic function by adding ... before the last parameter to accept any number of arguments as an array. This lets you call the function with multiple values without specifying each one separately.Syntax
A variadic function in PHP uses ... before the last parameter name to collect all extra arguments into an array. This parameter must be the last one in the function's parameter list.
Example syntax:
function exampleFunction(type ...$paramName) {
// $paramName is an array of all passed arguments
}php
function exampleFunction(...$args) { foreach ($args as $arg) { echo $arg . "\n"; } }
Example
This example shows a variadic function that sums any number of numbers passed to it and prints the total.
php
<?php function sumNumbers(int ...$numbers): int { return array_sum($numbers); } echo sumNumbers(1, 2, 3, 4); // Outputs 10 ?>
Output
10
Common Pitfalls
Common mistakes include placing the variadic parameter anywhere but last, which causes a syntax error. Also, forgetting that the variadic parameter is always an array can lead to errors when accessing its values.
Wrong example (variadic not last):
function wrong(...$args, $other) {}Correct example:
function correct($first, ...$args) {}php
/* Wrong: causes syntax error */ // function wrong(...$args, $other) {} /* Correct: variadic last */ function correct($first, ...$args) { echo $first . "\n"; foreach ($args as $arg) { echo $arg . "\n"; } } correct('start', 'middle', 'end');
Output
start
middle
end
Quick Reference
- Use
...before the last parameter to accept multiple arguments. - The variadic parameter is always an array inside the function.
- Variadic parameter must be last in the parameter list.
- Type hints can be used with variadic parameters (e.g.,
int ...$nums).
Key Takeaways
Use
... before the last parameter to create a variadic function in PHP.The variadic parameter collects all extra arguments into an array.
Always place the variadic parameter last in the function's parameter list.
You can add type hints to variadic parameters for better code clarity.
Access variadic arguments as an array inside the function.