Default arguments (or default parameters) in PHP allow you to assign a default value to a function parameter. If the caller does not provide a value for that parameter, PHP automatically uses the default value. This makes functions more flexible, easier to use, and reduces the need for overloaded functions.
What Are Default Arguments?
Default arguments are predefined parameter values used when no value is passed during a function call.
Example:
function greet($name = "Guest") {
echo "Hello, $name!";
}
If no argument is passed, "Guest" is used automatically.
Syntax
function functionName($param1 = defaultValue, $param2 = defaultValue) {
// code execution
}
Example 1: Basic Default Argument
function welcome($user = "Visitor") {
echo "Welcome, $user!";
}
welcome(); // Output: Welcome, Visitor!
welcome("Sagar"); // Output: Welcome, Sagar!
Example 2: Default Argument in Calculations
function multiply($a, $b = 2) {
return $a * $b;
}
echo multiply(5); // Output: 10 (5 * 2)
echo multiply(5, 4); // Output: 20
Example 3: Multiple Default Arguments
function orderPizza($size = "Medium", $crust = "Regular") {
echo "Order: $size Pizza with $crust Crust";
}
orderPizza();
Example 4: Using Non-Default + Default Together
Important rule:
➡ Default arguments must come after non-default arguments
function introduce($name, $greeting = "Hello") {
echo "$greeting, $name!";
}
introduce("Sagar");
❌ Wrong:
function intro($greeting = "Hello", $name) { }
Why Use Default Arguments?
- Makes functions easier to call
- Avoids multiple function overloads
- Makes code cleaner & more flexible
- Handles optional parameters gracefully
- Reduces error chances when arguments are missing
Real-World Use Cases
✔ API functions with optional filters
✔ Pagination functions (e.g., default page = 1)
✔ Message or notification systems
✔ Utility functions like string or math helpers
Citations
🔗 View other articles about PHP:
http://savanka.com/category/learn/php/
🔗 External PHP Documentation:
https://www.php.net/manual/en/