Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 147 ยท Functions

Parameters and Arguments

Learn PHP function parameters - default values, pass by reference, named arguments, variadic ...$args, argument unpacking and the optional-before-required rule.

A function becomes useful when it can work on different data each time you call it. Parameters are the variables a function declares in its signature; arguments are the actual values you pass when you call it. In function greet(string $name), $name is a parameter. In greet('Ana'), 'Ana' is the argument.

PHP gives you a rich toolbox here: default values, passing by reference, named arguments (PHP 8.0), variadic functions that accept any number of values, and argument unpacking with .... This lesson covers all of them, plus the rules and error messages you'll meet when you get them wrong. You should already know how to define and call a function from Functions.

Parameters and arguments

Each parameter is a local variable that PHP fills with the matching argument, in order, when the function starts. PHP copies the value in (for arrays and strings it does this cheaply, copying only if you change them), so changing a parameter inside the function doesn't change the caller's variable.

PHP Parameters receive copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is 6 x notebook, then count is still 3. The function doubled its own $quantity, not your $count.

declare(strict_types=1); on the first line tells PHP not to convert argument types for you: passing '3' to an int parameter becomes an error instead of silently turning into 3. You'll learn exactly what it affects in Type Declarations. This lesson uses it in every multi-function example, as modern PHP code does.

Too few and too many arguments

If you leave out a required argument, PHP throws an ArgumentCountError before the function body runs. Changing line 11 of the example above to echo describe('notebook'); stops the script with:

TEXT
Fatal error: Uncaught ArgumentCountError: Too few arguments to function describe(), 1 passed in main.php on line 11 and exactly 2 expected

Extra arguments are different: PHP silently accepts them for user-defined functions. They're still available through func_get_args(), but modern code uses variadic parameters instead (covered below). Built-in functions are stricter and throw an ArgumentCountError for extra arguments too.

Default values

A parameter with = value is optional. If the caller leaves it out, the default is used:

PHP Optional parameters with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints 1,234.50 USD, 1,234.50 EUR and 1,235 JPY.

A default must be a constant expression: a literal, a constant, an array of literals, or (since PHP 8.1) new SomeClass(). You can't use a function call or a variable as a default:

PHP
function log1(string $message, string $time = date('H:i')) {} // Fatal error: Constant expression contains invalid operations
function log2(string $message, ?string $time = null)          // the usual fix
{
    $time ??= date('H:i');
    // ...
}

The null default plus ??= (see Null Coalescing and Ternary) is the standard pattern when the real default must be computed at call time.

Defaults are evaluated on every call, not once. That avoids a famous Python trap: a default array $items = [] is a fresh empty array each time.

Optional parameters go last

Positional arguments fill parameters from left to right, so an optional parameter before a required one can never actually be skipped. PHP 8.0 deprecated that order, and the default is ignored:

PHP Optional before required is deprecated

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This example shows the diagnostic on purpose:

TEXT
Deprecated: makeTag(): Optional parameter $tag declared before required parameter $text is implicitly treated as a required parameter in main.php on line 2

The function still works when you pass both arguments, but $tag is now effectively required. Fix it by moving optional parameters to the end of the list.

A related relic: old code often wrote Foo $x = null just to make a typed parameter accept null. PHP 8.4 deprecates this implicitly nullable type ("Implicitly marking parameter $x as nullable is deprecated"), so write the nullable type explicitly: ?Foo $x = null.

Named arguments (PHP 8.0)

Named arguments let you pass a value by the parameter's name instead of its position: name: value. They make calls self-documenting and let you skip optional parameters you don't want to change.

PHP Calling with named arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
19.999 USD
1,500 SEK
007
<b>"Hi"</b>

Before PHP 8.0, changing the third parameter meant repeating the second one's default by hand. With decimals: 3 you say exactly what you mean. Named arguments are especially handy for boolean flags: json_decode($json, associative: true) is far clearer than json_decode($json, true).

The rules

  • Positional arguments must come before named ones. formatPrice(currency: 'EUR', 10.0) is a compile-time error: "Cannot use positional argument after named argument".
  • You can't pass the same parameter twice. formatPrice(10.0, amount: 5.0) throws Error: Named parameter $amount overwrites previous argument.
  • An unknown name throws Error: Unknown named parameter $colour.
  • Required parameters still need a value, by position or by name.

Named arguments make parameter names part of a function's public API. If you rename $currency to $code in a library, every caller using currency: breaks. Choose parameter names carefully in code other people call.

Passing by reference

Sometimes a function should change the caller's variable. Put & before the parameter name to receive a reference instead of a copy. The parameter and the caller's variable then become two names for the same value.

PHP Changing the caller's variable with a reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

$total becomes 100, and $cart ends up as apple, bread, milk. Notice that the & goes in the function definition only; the call looks normal. That's convenient but also hides the fact that addTax($total, ...) modifies $total, which is one reason to use references sparingly.

Many built-in functions take references: sort($array) sorts your array in place, preg_match($pattern, $text, $matches) fills $matches, and array_push($stack, $value) changes $stack. You can only pass something that has a storage location, such as a variable, an array element or a property. Passing a literal fails:

TEXT
Fatal error: Uncaught Error: addTax(): Argument #1 ($price) could not be passed by reference

Returning a value is usually clearer than modifying a reference: $total = withTax($total, 0.25); shows the change right at the call. Use references when a function genuinely needs to update several things in place, or when a large array would otherwise be rebuilt on every call in a hot loop.

References in general (including foreach by reference) are covered in Variables and foreach Loops.

Variadic functions: ...$args

A variadic parameter collects any number of remaining arguments into an array. Write ... before the last parameter's name:

PHP Accepting any number of arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints 18, 0 and <div class="card card-wide shadow">. (Output here is plain text; on a web page you'd escape dynamic values with htmlspecialchars before printing tags like this.)

A few rules:

  • The variadic parameter must be the last one, and there can be only one.
  • A type applies to every collected value: float ...$numbers accepts only numbers.
  • Inside the function it's always an array, empty if no extra arguments were passed.
  • With &...$refs, every collected argument is passed by reference.

If the caller uses named arguments that don't match any regular parameter, a variadic parameter collects them with string keys:

PHP
function config(string ...$options): void
{
    print_r($options);
}

config('debug', mode: 'fast', level: 'high');
// Array ( [0] => debug [mode] => fast [level] => high )

Unpacking arguments with ...

The same ... works at the call site, in reverse: it spreads an array (or any Traversable) into separate arguments.

PHP Spreading arrays into arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is 2026-03-09, 2025-12-31, 1999-01-01 and max: 23. Since PHP 8.1, string keys are treated as parameter names, so an associative array can supply arguments in any order. Before that, unpacking an array with string keys was an error.

Unpacking and variadics combine naturally into wrapper functions that pass everything through:

PHP
function logged(callable $fn, mixed ...$args): mixed
{
    echo 'calling with ', count($args), " argument(s)\n";
    return $fn(...$args);
}

You'll see this pattern again with callables in Anonymous Functions and Closures.

Choosing a good signature

A few habits keep functions easy to call:

  • Keep the parameter list short. Three or four parameters is plenty. Beyond that, group related values into an array shape or, better, a small class (see Constructors).
  • Required first, optional last, most commonly changed optional parameters earliest.
  • Avoid boolean flag parameters like render($data, true, false). If you keep them, encourage callers to use named arguments: render($data, escape: true). Often two separate functions are clearer.
  • Prefer return values over references unless you have a clear reason.
  • Add types to every parameter. They document intent and catch mistakes early; the next lesson goes deep.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given function f(int $a, int $b = 2, int $c = 3), what does f(1, c: 9) pass to $b?

    Named arguments let you skip optional parameters. $b keeps its default of 2, and $c receives 9.
  2. 2. What happens with function bump(int &$n): void { $n++; } and $x = 5; bump($x); echo $x;?

    The & in the definition makes $n a reference to $x, so incrementing $n changes $x. The call itself needs no &.
  3. 3. Which call is a compile-time error for function g(string $a, string $b)?

    Positional arguments can't follow named ones. The other three calls are valid.
  4. 4. What is $numbers inside function sum(int ...$numbers) when you call sum()?

    A variadic parameter is always an array. With no extra arguments, it's an empty array.
  5. 5. Why does PHP 8 emit a deprecation for function h($x = 1, $y) {}?

    PHP treats $x as required anyway and warns you. Move optional parameters after required ones.

Summary

  • Parameters are declared in the signature; arguments are the values passed. Parameters get copies, so changing them doesn't affect the caller.
  • Missing required arguments throw ArgumentCountError; extra ones are ignored by user functions.
  • Default values ($x = 10) make parameters optional. They must be constant expressions; use a null default plus ??= for computed defaults. Put optional parameters last (PHP 8 deprecates the reverse).
  • Named arguments (PHP 8.0) like decimals: 3 skip optional parameters and document calls. Positional ones come first; names become part of your API.
  • &$param passes by reference, so the function can change the caller's variable. Only variables (not literals) can be passed. Prefer return values.
  • ...$args collects any number of arguments into an array; at a call, ...$array unpacks an array into arguments, with string keys acting as names (PHP 8.1).

Next: Type Declarations