PHP allows developers to assign default values to function parameters, which are used when the corresponding arguments are omitted.

- Default values are used when the corresponding arguments are omitted.
- Arguments passed during a function call override the default values.
- Required parameters should generally be declared before parameters with default values.
Default Values for Function Parameters
A default parameter is defined by assigning a value to a parameter in the function declaration.
Syntax:
function greeting($name = "GeeksforGeeks") {
// Function body
}
Here, $name has a default value of "GeeksforGeeks". If no argument is provided, the function uses this value.
Default Values for Missing Arguments
When a function is called without an argument for a parameter with a default value, PHP uses the predefined value. If an argument is provided, PHP uses the supplied value instead.
Example:
<?php
function greeting($name = "GeeksforGeeks") {
echo "Welcome to $name\n";
}
greeting("GFG");
greeting();
greeting("A Computer Science Portal");
?>
- greeting("GFG") uses "GFG" as the argument.
- greeting() uses the default value "GeeksforGeeks".
- greeting("A Computer Science Portal") uses the supplied argument.
Default Values for Multiple Parameters
PHP allows multiple parameters in a function to have default values. If arguments are omitted, the corresponding parameters use their default values.
Example:
<?php
function welcome(
$first = "GeeksforGeeks",
$last = "A Computer Science Portal for Geeks"
) {
echo "Greeting: $first $last\n";
}
welcome();
welcome("xyz");
welcome("xyz", "Contributor");
?>
- welcome() uses the default values for both parameters.
- welcome("xyz") overrides $first and uses the default value for $last.
- welcome("xyz", "Contributor") overrides both default values.
Required Parameters Before Default Parameters
Required parameters should generally appear before parameters with default values. This allows PHP to identify the required arguments clearly when the function is called.
Example:
<?php
function calculateTotal($price, $tax = 5) {
return $price + ($price * $tax / 100);
}
echo calculateTotal(100) . "\n";
echo calculateTotal(100, 10);
?>
- calculateTotal(100) uses the default tax rate of 5% and returns 105.
- calculateTotal(100, 10) uses the supplied tax rate of 10% and returns 110.
Note: In PHP, a parameter with a default value can be omitted when calling the function. However, if a required parameter follows an optional parameter, the default value may not make the earlier parameter truly optional in practice. Declare required parameters before optional parameters to avoid this issue.