Home >Backend Development >PHP Tutorial >How to create a function with variable number of parameters in PHP?
In PHP, three dots (...) can be used to create a function with a variable number of parameters, which will be stored in an array. The variable number of arguments must be the last argument in the function argument list, and the variable number of arguments array can be retrieved using the func_get_args() function.
#How to create a function with a variable number of parameters in PHP?
Introduction
PHP functions can accept a variable number of arguments, which makes it easy to write functions that accept different numbers of input arguments. This is useful in dynamic languages, where the exact number of arguments cannot be known when the function is defined.
Syntax
To create a function with a variable number of arguments, use three dots (...) in the function parameter list, as shown below:
function myFunction(...$args) { // 代码 }
...$args
Represents an array containing all arguments passed to the function.
Practical case
Create a function to calculate the sum of all elements in an array:
function sumArray(...$numbers) { $total = 0; foreach ($numbers as $number) { $total += $number; } return $total; } // 示例用法 $result = sumArray(1, 2, 3, 4, 5); // 结果:15
Note
func_get_args()
function to retrieve a variable number of argument arrays. function sumArray(int ...$numbers) { // 代码 }
This will force all passed parameters to be integers.
Hope this article helps you create functions with variable number of parameters in PHP.
The above is the detailed content of How to create a function with variable number of parameters in PHP?. For more information, please follow other related articles on the PHP Chinese website!