Default and Variadic Arguments
Named arguments, variadic parameters, and collecting an unknown number of values.
2 min read
Beyond simple default values, PHP supports two features that make function calls more flexible: named arguments and variadic parameters.
Named arguments
<?php
function createUser(string $name, string $role = "member", bool $isActive = true) {
return "$name ($role) — active: " . ($isActive ? "yes" : "no");
}
echo createUser(name: "Amara", isActive: false);Named arguments let you specify parameters by name rather than position, in any order, and skip over defaults you don't want to override — here, role keeps its default "member" while isActive is set explicitly, without needing to also repeat role just to reach it positionally.
Mixing positional and named arguments
<?php
createUser("Diego", isActive: false);Positional arguments must come first, but any parameter after them can be passed by name. This is especially useful for functions with several boolean or optional parameters, where a plain positional call like createUser("Diego", "member", false) forces the reader to go count parameters to know what false even means.
Variadic parameters: collecting extra arguments
<?php
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10The ... before a parameter name collects any number of remaining arguments into a single array ($numbers here). This is how PHP handles functions that accept a variable number of arguments, like a sum() that should work whether it's called with two numbers or twenty.
Combining fixed and variadic parameters
<?php
function logMessage(string $level, ...$details) {
echo strtoupper($level) . ": " . implode(", ", $details);
}
logMessage("error", "Connection failed", "Retrying in 5s");A variadic parameter must be the last one in the parameter list — any fixed parameters before it are filled first, and everything remaining is gathered into the variadic array.
Spreading an array into arguments
<?php
function add($a, $b, $c) {
return $a + $b + $c;
}
$numbers = [1, 2, 3];
echo add(...$numbers); // 6The same ... operator works in reverse at the call site: prefixing an array with ... spreads its elements out as individual arguments, rather than passing the array itself as one argument. This pairs naturally with a variadic function on the receiving end, but works with any function expecting that many individual arguments.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.