PHP Variable Arguments
In PHP, variable arguments allow a function to accept an indefinite number of arguments at runtime. This is achieved by using the ellipsis symbol ...
in the function definition.
Syntax
function functionName(...$variableName) {
// function body
}
Example
function sum(...$numbers) {
$result = 0;
foreach ($numbers as $number) {
$result += $number;
}
return $result;
}
echo sum(2, 3, 4); // Output: 9
echo sum1, 2, 3, 4, 5); // Output: 15
Output
The above example will output:
9
15
Explanation
In the example, the sum()
function is defined with variable arguments using the ellipsis symbol ...
. When the function is called with a list of numbers as arguments, PHP creates an array with those numbers and passes it to the function.
Within the sum()
function, we loop through the $numbers
array using a foreach
loop and add up the numbers to get the total sum. Finally, we return the sum as the result of the function.
Use
Variable arguments are useful when you want to write a function that can accept a variable number of arguments, such as a function to calculate the sum or average of a list of numbers, a function to concatenate multiple strings, etc.
By using variable arguments, you can avoid having to define multiple functions with different numbers of arguments or having to pass an array as an argument to the function.
Important Points
- The variable arguments must follow any regular arguments in the function definition.
- The variable arguments are packed into an array and passed to the function as the last argument.
- The variable arguments can have any type, including mixed types.
- The variable arguments must be passed by value; passing them by reference is not allowed.
Summary
Variable arguments in PHP allow functions to accept an indefinite number of arguments at runtime. Variable arguments are defined using the ellipsis symbol ...
in the function definition. Within the function, the variable arguments are packed into an array and can be accessed using a loop or other array methods. Variable arguments are useful when you want to write a function that can accept a variable number of arguments without having to define multiple functions or pass an array as an argument.