PHP Function Arguments & Default Values
Function parameters let you pass data into a function so it can work with different inputs each time it is called. PHP also lets you set default values for parameters, which are used if no argument is provided for them.
PHP supports named arguments (calling a function using parameter names instead of position) and variable-length argument lists using the ... (spread) operator, giving you flexibility in how functions are called.
function myFunc($param = "default") { }
function sum(...$numbers) { }Default parameter values
You can assign a default value to a parameter in the function definition. If the caller omits that argument, the default value is used instead.
Variable-length arguments
Using ...$args in a function definition collects any number of extra arguments into an array, which you can then loop through inside the function.
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}
greet();
echo " ";
greet("Amy");
?>Hello, Guest! Hello, Amy!When no argument is given, the default value "Guest" is used.
<?php
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4);
?>10The ... operator gathers all passed arguments into a single array inside the function.
Key points
- Default parameter values are used when no argument is supplied.
- The ... operator collects variable numbers of arguments into an array.
- Named arguments let you pass values by parameter name.
- Default parameters must come after required parameters in the definition.
