In PHP, default values for function parameters can be specified using the assignment operator (=) in the function declaration. This allows the function to have default values for parameters if no value is provided when the function is called.
To specify a default value for a parameter, you simply assign a value to the parameter in the function declaration. For example, consider the following function declaration:
php
function greet($name = 'Guest') {
echo "Hello, $name!";
}
In this example, the parameter `$name` has a default value of `'Guest'`. If the function is called without providing a value for `$name`, it will default to `'Guest'`. For instance, calling `greet()` will output "Hello, Guest!".
If a value is provided when calling the function, it will override the default value. For example:
php
greet('John');
This will output "Hello, John!" instead of using the default value.
It is important to note that when specifying default values for parameters, they should be placed at the end of the parameter list. This means that any parameters with default values must come after the parameters without default values. For example:
php
function greet($name, $age = 18) {
echo "Hello, $name! You are $age years old.";
}
In this case, `$name` is a required parameter, while `$age` has a default value of 18. If the function is called without providing a value for `$age`, it will default to 18. However, if a value is provided, it will override the default value.
Default values can also be expressions or variables. For example:
php
$defaultName = 'Guest';
function greet($name = $defaultName) {
echo "Hello, $name!";
}
In this example, the default value for `$name` is the variable `$defaultName`. If the variable is not defined or has a null value, it will default to `'Guest'`.
Default values for function parameters in PHP can be specified using the assignment operator (=) in the function declaration. This allows functions to have default values for parameters if no value is provided when the function is called. Default values can be simple values, expressions, or variables. By understanding how to specify default values, developers can create more flexible and reusable functions in their PHP code.
Other recent questions and answers regarding Examination review:
- What is the purpose of the "return" statement in PHP functions?
- How can we pass arguments to our own functions in PHP?
- What are arguments and parameters in PHP functions?
- How are functions defined in PHP?

