Introduction
Default arguments allow PHP functions to use predefined values when an argument is not provided. Named arguments let you pass values using parameter names instead of depending on their order. In this chapter, you will practise both features using simple examples involving students, employees, products, and salary calculations. Default Arguments and Named Arguments in PHP Solved Practice Questions to help you to understand the concepts.
Question 1: Create a Function with One Default Argument
Problem Statement:
Create a function named displayWelcome() that accepts a student’s name. Set the default name as Student and display a welcome message.
PHP Solution:
<?php
function displayWelcome($name = "Student") {
echo "Welcome, " . $name . "\n";
}
displayWelcome();
displayWelcome("Rahul");
?>
Sample Output:
Welcome, Student
Welcome, Rahul
Explanation:
$name = "Student"sets a default argument value.- The first function call does not provide an argument, so PHP uses
Student. - The second function call provides
Rahul, which replaces the default value.
Concepts Covered:
- Default arguments
- Function parameters
- Optional arguments
Question 2: Use Multiple Default Arguments
Problem Statement:
Create a function named studentDetails() that accepts a student’s name, course, and city. Set default values for the course and city.
PHP Solution:
<?php
function studentDetails($name, $course = "PHP", $city = "Delhi") {
echo "Name: " . $name . "\n";
echo "Course: " . $course . "\n";
echo "City: " . $city . "\n\n";
}
studentDetails("Amit");
studentDetails("Priya", "Python");
studentDetails("Rahul", "Java", "Mumbai");
?>
Sample Output:
Name: Amit
Course: PHP
City: Delhi
Name: Priya
Course: Python
City: Delhi
Name: Rahul
Course: Java
City: Mumbai
Explanation:
$nameis a required parameter.$courseand$cityhave default values.- The first call uses both default values.
- The second call changes the course but keeps the default city.
- The third call provides all three arguments.
Concepts Covered:
- Multiple default arguments
- Required parameters
- Optional parameters
Question 3: Override a Default Argument
Problem Statement:
Create a function named calculateDiscount() that accepts a product price and a discount percentage. Set the default discount to 10%. Calculate and return the final price.
PHP Solution:
<?php
function calculateDiscount($price, $discount = 10) {
$discountAmount = ($price * $discount) / 100;
return $price - $discountAmount;
}
echo "Price After Default Discount: " . calculateDiscount(1000) . "\n";
echo "Price After Custom Discount: " . calculateDiscount(1000, 20);
?>
Sample Output:
Price After Default Discount: 900
Price After Custom Discount: 800
Explanation:
- The default discount is 10%.
- The first call uses the default discount.
- The second call supplies a custom discount of 20%.
- The function returns the final price after deducting the discount.
Concepts Covered:
- Default argument values
- Overriding default arguments
- Returning calculated values
Question 4: Use Named Arguments in a Function Call
Problem Statement:
Create a function named employeeDetails() that accepts an employee’s name, department, and salary. Call the function using named arguments.
PHP Solution:
<?php
function employeeDetails($name, $department, $salary) {
echo "Employee Name: " . $name . "\n";
echo "Department: " . $department . "\n";
echo "Salary: " . $salary;
}
employeeDetails(
name: "Amit",
department: "IT",
salary: 35000
);
?>
Sample Output:
Employee Name: Amit
Department: IT
Salary: 35000
Explanation:
- Named arguments use parameter names when passing values.
name,department, andsalarymatch the function’s parameter names.- PHP assigns each value to the correct parameter.
Concepts Covered:
- Named arguments
- Parameter names
- Function calling
Question 5: Change the Order of Named Arguments
Problem Statement:
Create a function named productDetails() that accepts a product name, price, and category. Call the function by passing named arguments in a different order.
PHP Solution:
<?php
function productDetails($name, $price, $category) {
echo "Product: " . $name . "\n";
echo "Price: " . $price . "\n";
echo "Category: " . $category;
}
productDetails(
category: "Electronics",
price: 25000,
name: "Laptop"
);
?>
Sample Output:
Product: Laptop
Price: 25000
Category: Electronics
Explanation:
- Named arguments allow you to change the order of supplied values.
- Each value is assigned according to its parameter name.
- The function still receives the correct product information.
Concepts Covered:
- Named argument order
- Parameter matching
- Flexible function calls
Question 6: Skip a Default Argument Using Named Arguments
Problem Statement:
Create a function named courseDetails() that accepts a course name, duration, and mode. Set default values for duration and mode. Call the function by changing only the mode while keeping the default duration.
PHP Solution:
<?php
function courseDetails($course, $duration = "3 Months", $mode = "Online") {
echo "Course: " . $course . "\n";
echo "Duration: " . $duration . "\n";
echo "Mode: " . $mode . "\n";
}
courseDetails(
course: "PHP",
mode: "Classroom"
);
?>
Sample Output:
Course: PHP
Duration: 3 Months
Mode: Classroom
Explanation:
$durationhas a default value of3 Months.$modehas a default value ofOnline.- The function call supplies
courseandmodeby name. - PHP uses the default duration because no value was provided for it.
Concepts Covered:
- Named arguments
- Default arguments
- Skipping optional parameters
Question 7: Combine Default and Named Arguments in Salary Calculation
Problem Statement:
Create a function named calculateSalary() that accepts basic salary, allowance, and deduction. Set the default allowance to ₹3,000 and deduction to ₹1,000. Use named arguments to change the deduction.
PHP Solution:
<?php
function calculateSalary($basicSalary, $allowance = 3000, $deduction = 1000) {
return $basicSalary + $allowance - $deduction;
}
$netSalary = calculateSalary(
basicSalary: 30000,
deduction: 2000
);
echo "Net Salary: " . $netSalary;
?>
Sample Output:
Net Salary: 31000
Explanation:
- The basic salary is ₹30,000.
- The allowance uses its default value of ₹3,000.
- The deduction is changed to ₹2,000 using a named argument.
- The function returns the calculated net salary.
Concepts Covered:
- Combining default and named arguments
- Salary calculation
- Returning function results
Question 8: Use Named Arguments with Boolean Parameters
Problem Statement:
Create a function named showStudentStatus() that accepts a student’s name and two Boolean values: isActive and hasPaidFees. Set both Boolean parameters to true by default. Use named arguments to change the fee status.
PHP Solution:
<?php
function showStudentStatus($name, $isActive = true, $hasPaidFees = true) {
echo "Student: " . $name . "\n";
echo "Active: " . ($isActive ? "Yes" : "No") . "\n";
echo "Fees Paid: " . ($hasPaidFees ? "Yes" : "No") . "\n";
}
showStudentStatus(
name: "Priya",
hasPaidFees: false
);
?>
Sample Output:
Student: Priya
Active: Yes
Fees Paid: No
Explanation:
- Both Boolean parameters have default values of
true. - The function call changes only
hasPaidFeestofalse. - The
isActiveparameter keeps its default value. - The ternary operator displays readable Yes or No messages.
Concepts Covered:
- Boolean default arguments
- Named arguments
- Ternary operator
Question 9: Use Named Arguments with a Return Value
Problem Statement:
Create a function named calculateRectangleArea() that accepts length and width. Set the default width to 5. Use a named argument to provide only the length and return the rectangle’s area.
PHP Solution:
<?php
function calculateRectangleArea($length, $width = 5) {
return $length * $width;
}
$area = calculateRectangleArea(
length: 12
);
echo "Rectangle Area: " . $area;
?>
Sample Output:
Rectangle Area: 60
Explanation:
- The function accepts length and width.
- The default width is 5.
- The function call provides only the length using a named argument.
- PHP uses the default width and returns the calculated area.
Concepts Covered:
- Named arguments
- Default parameter values
- Returning calculated results
Question 10: Build an Employee Salary Report Using Default and Named Arguments
Problem Statement:
Create a function named employeeSalaryReport() that accepts employee name, basic salary, allowance, and deduction. Set the default allowance to ₹5,000 and deduction to ₹2,000. Use named arguments to provide the employee details and change the allowance.
PHP Solution:
<?php
function employeeSalaryReport(
$name,
$basicSalary,
$allowance = 5000,
$deduction = 2000
) {
$grossSalary = $basicSalary + $allowance;
$netSalary = $grossSalary - $deduction;
return [
"name" => $name,
"basic_salary" => $basicSalary,
"allowance" => $allowance,
"deduction" => $deduction,
"gross_salary" => $grossSalary,
"net_salary" => $netSalary
];
}
$report = employeeSalaryReport(
name: "Rahul",
basicSalary: 40000,
allowance: 7000
);
echo "Employee Name: " . $report["name"] . "\n";
echo "Basic Salary: " . $report["basic_salary"] . "\n";
echo "Allowance: " . $report["allowance"] . "\n";
echo "Deduction: " . $report["deduction"] . "\n";
echo "Gross Salary: " . $report["gross_salary"] . "\n";
echo "Net Salary: " . $report["net_salary"];
?>
Sample Output:
Employee Name: Rahul
Basic Salary: 40000
Allowance: 7000
Deduction: 2000
Gross Salary: 47000
Net Salary: 45000
Explanation:
- The function accepts employee details and salary components.
- The allowance is changed to ₹7,000 using a named argument.
- The deduction keeps its default value of ₹2,000.
- Gross salary is calculated by adding basic salary and allowance.
- Net salary is calculated after subtracting the deduction.
- The function returns all salary details in an associative array.
Concepts Covered:
- Default arguments
- Named arguments
- Associative arrays
- Salary calculations
- Returning multiple results
Key Takeaways
- Default arguments provide predefined values for function parameters.
- Named arguments pass values using parameter names.
- Default arguments make function parameters optional.
- Required parameters should generally be declared before optional parameters.
- Named arguments allow you to change the order of supplied values.
- Named arguments can skip optional parameters.
- You can combine default and named arguments in the same function call.
- Named arguments are supported from PHP 8.0 onward.
- Parameter names must match the names declared in the function definition.
Frequently Asked Questions (FAQs)
1. What are default arguments in PHP?
Default arguments are predefined values assigned to function parameters. PHP uses these values when the caller does not provide the corresponding arguments.
2. What are named arguments in PHP?
Named arguments allow you to pass values to a function by specifying the parameter names instead of relying only on their order.
3. What is the difference between default and named arguments?
Default arguments provide values when arguments are omitted. Named arguments identify which parameter should receive a supplied value.
4. Can we use multiple default arguments in PHP?
Yes. A PHP function can have multiple parameters with default values.
5. Can we change the order of named arguments?
Yes. Named arguments can be passed in a different order because PHP matches values using parameter names.
6. Can we skip a default argument in PHP?
Yes. You can skip an optional parameter by using named arguments to provide a value for a later parameter.
7. Which PHP version supports named arguments?
Named arguments were introduced in PHP 8.0.
8. Can default and named arguments be used together?
Yes. You can define default values in a function and use named arguments when calling it to override selected values.
9. Can required parameters come after optional parameters?
Required parameters should be declared before optional parameters. This keeps function calls clear and avoids confusing parameter behaviour.
10. What happens if a named argument uses an incorrect parameter name?
PHP generates an error because the supplied argument name does not match a parameter in the function definition.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
