Home > Backend Development > PHP Tutorial > How to make a PHP function accept a variable number of arguments?

How to make a PHP function accept a variable number of arguments?

WBOY
Release: 2024-04-15 12:36:01
Original
690 people have browsed it

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.

如何让 PHP 函数接受可变数量的参数?

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) {
    // 函数代码
}
Copy after login

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
Copy after login

In the above example,

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 variable number of parameters must be the last parameter in the function parameter list.
  • When passing parameters to a function that accepts a variable number of parameters, you can pass the array directly as a parameter without unwinding the array. For example,
  • sum([1, 2, 3, 4, 5]).

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template