Back to results for “Scope”
PHP › Functions & Scope

What are default parameter values and variadic functions in PHP, and how do they add flexibility to how a function can be called?

Intermediate

Answer

A default parameter value lets you specify a fallback value that is used if the caller does not explicitly provide that argument, making certain parameters effectively optional, while a variadic function, defined using an ellipsis before the parameter name, lets a function accept any number of arguments, which are collected into a single array inside the function, giving your functions flexible, convenient calling patterns without requiring the caller to always supply every single possible argument.
function greet($name, $greeting = 'Hello') {
    return "$greeting, $name!";
}

function sum(...$numbers) {
    return array_sum($numbers);
}
echo sum(1, 2, 3, 4);
Real-world example A logging function accepts a variadic list of context values, letting calling code pass anywhere from zero to many additional pieces of context information without the function's signature needing to change to accommodate different call patterns.

Common follow-ups: What happens if you try to call a function without providing a required parameter that has no default value?;Can a function have both regular parameters and a variadic parameter together?