What is the best practice for handling optional parameters in PHP functions?
When dealing with optional parameters in PHP functions, it is best practice to set default values for those parameters to avoid potential errors when the parameter is not provided. This ensures that the function can still be called without all parameters being passed. By setting default values, you can control the behavior of the function when certain parameters are not provided.
function greet($name, $age = 18) {
echo "Hello, $name! You are $age years old.";
}
// Calling the function with both parameters
greet("Alice", 25);
// Calling the function with only the required parameter
greet("Bob");