PHP ยท Chapter 18 of 44

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.

Syntax
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.

Example 1 (php)
<?php
  function greet($name = "Guest") {
    echo "Hello, $name!";
  }
  greet();
  echo " ";
  greet("Amy");
?>
Output
Hello, Guest! Hello, Amy!

When no argument is given, the default value "Guest" is used.

Example 2 (php)
<?php
  function sum(...$numbers) {
    return array_sum($numbers);
  }
  echo sum(1, 2, 3, 4);
?>
Output
10

The ... 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.
๐Ÿ’ก Note: Named arguments (PHP 8+) let you skip optional parameters cleanly, like myFunc(name: "Amy").

๐Ÿ“ Quick Quiz

1. What happens if a parameter has a default value and no argument is passed?

2. What does the ... operator do in a function definition?

3. Where must default parameters be placed?