How to Use Default Parameter in PHP: Simple Guide
In PHP, you can set a
default parameter by assigning a value to a function argument in the function definition, like function example($param = 'default'). This makes the parameter optional when calling the function, and if no argument is passed, the default value is used.Syntax
The syntax for default parameters in PHP functions involves assigning a value to a parameter in the function declaration. This value is used if no argument is provided when calling the function.
- function: keyword to declare a function.
- functionName: the name of the function.
- ($param = defaultValue): parameter with a default value.
php
function functionName($param = 'defaultValue') { // function body }
Example
This example shows a function with a default parameter. If you call the function without an argument, it uses the default value. If you provide an argument, it uses that instead.
php
<?php function greet($name = 'Friend') { echo "Hello, $name!"; } greet(); // Uses default parameter echo "\n"; greet('Alice'); // Uses provided argument ?>
Output
Hello, Friend!
Hello, Alice!
Common Pitfalls
One common mistake is placing a parameter with a default value before a parameter without one. In PHP, all parameters with default values must come after parameters without defaults.
Incorrect order causes a syntax error.
php
<?php // Wrong: default parameter before non-default // function example($param1 = 'default', $param2) { // echo "$param1 and $param2"; // } // Correct order: function example($param1, $param2 = 'default') { echo "$param1 and $param2"; } example('Hello'); // Outputs: Hello and default ?>
Output
Hello and default
Quick Reference
Remember these tips when using default parameters in PHP:
- Default parameters must be at the end of the parameter list.
- Default values can be any valid PHP expression.
- If no argument is passed, the default value is used.
- You can override the default by passing an argument.
Key Takeaways
Set default values in function parameters by assigning them in the function definition.
Always place parameters with default values after those without defaults.
Calling a function without an argument uses the default parameter value.
You can override default parameters by passing explicit arguments.
Default parameters help make function arguments optional and your code cleaner.