Function Parameter Default Value / Optional Parameter

Quick Summary
- Give a PHP function parameter a default value to make it optional, so PHP uses the default when the caller leaves it out.
- Optional parameters must follow required ones; a default before a required parameter is ignored, and recent PHP versions flag it as deprecated.
- In the example, serve() has defaults for both parameters, so it runs with two arguments, one argument or none at all.
In PHP you can give a function parameter a default value. That parameter becomes optional: if the caller leaves it out, PHP uses the default instead. The one rule to remember is that optional parameters must come after the required ones.
Parameter order matters
This version gives $items a default but leaves $food_name, which comes after it, without one.
function serve( $items="2",$food_name ) {
echo "{$items} of {$food_name} has been served";
}The default on $items is useless here. Arguments are matched by position, so you can’t skip the first one and still pass the second, and PHP treats $items as required anyway. Recent PHP versions also show a deprecation notice for this. To fix it, give a default to every parameter from the first optional one to the end of the list: either to both parameters, as in the example below, or only to the last one, as in function serve( $items, $food_name = "noodles" ).
A working example
The example is split into two files. The main file loads functions.php with include_once and calls serve() with both arguments. Splitting code into files this way is also how you can organize a WordPress functions.php.
<?php
include_once "functions.php";
serve ("10 plates", "Ramen");In functions.php, serve() has a default value for both parameters. The curly braces inside the double-quoted string insert the variable values into the text.
<?php
function serve( $items="2 plates",$food_name="noodles" ) {
echo "{$items} of {$food_name} has been served";
}With this function:
serve( "10 plates", "Ramen" )prints 10 plates of Ramen has been served.serve( "3 bowls" )prints 3 bowls of noodles has been served, because the missing second argument falls back to its default.serve()prints 2 plates of noodles has been served.
Related articles
- variadic parameters: accept any number of arguments instead of a fixed list
- parameter and return type declarations: typed parameters can have defaults too
