Use the... operator in PHP to create a variable parameter function, which packs extra parameters into an array: function syntax: function functionName(...$argumentName) {}For example: sum(...$numbers ) function calculates the sum of the numbers in an array. A variable number of arguments must be the last argument in the function argument list. When passing parameters to variadic functions, you can pass arrays directly as parameters.
Let PHP functions accept a variable number of parameters
In PHP, you can use ...## The # operator creates functions that accept a variable number of arguments. This operator allows all extra parameters passed to the function to be packed into an array.
Syntax:
function functionName(...$argumentName) { // 函数代码 }
For example:
// 计算一个数组中所有数字的总和 function sum(...$numbers) { $total = 0; foreach ($numbers as $number) { $total += $number; } return $total; } // 实战案例 $numbers = [1, 2, 3, 4, 5]; echo sum($numbers); // 输出:15
sum() Function can accept any number of parameters. All numbers passed to the function will be packed into the
$numbers array, and the function will sum all the numbers in that array.
Note:
.
The above is the detailed content of How to make a PHP function accept a variable number of arguments?. For more information, please follow other related articles on the PHP Chinese website!