Introduction to User-Defined Functions in PHP

Introduction

Introduction to User-Defined Functions in PHP allow you to create your own reusable blocks of code to perform specific tasks. Instead of writing the same code repeatedly, you can define a function once and call it whenever needed. In this chapter, you will learn to create, call, reuse, and organize functions through practical PHP questions covering function declarations, parameters, return values, and default arguments.

Question 1: Create a Simple Function to Display a Message

Problem Statement

Create a user-defined function named welcomeMessage() that displays a welcome message. Call the function to execute it.

PHP Solution

<?php
function welcomeMessage() {
    echo "Welcome to PHP Programming!";
}

welcomeMessage();
?>

Sample Output

Welcome to PHP Programming!

Explanation

The function keyword is used to declare a user-defined function. The function name is welcomeMessage(). When you call the function using welcomeMessage();, PHP executes the code inside its body.

Concepts Covered

  • User-defined functions
  • Function declaration
  • Function calling
  • echo statement

Question 2: Create a Function to Display Student Details

Problem Statement

Create a function named studentDetails() that displays a student’s name, course, and city. Call the function to display the details.

PHP Solution

<?php
function studentDetails() {
    echo "Student Name: Rahul\n";
    echo "Course: PHP\n";
    echo "City: Delhi\n";
}

studentDetails();
?>

Sample Output

Student Name: Rahul
Course: PHP
City: Delhi

Explanation

The studentDetails() function contains three echo statements. When the function is called, all three statements execute in order. A function can contain multiple statements to complete a task.

Concepts Covered

  • Function declaration
  • Multiple statements inside a function
  • Function calling
  • Displaying information

Question 3: Call the Same Function Multiple Times

Problem Statement

Create a function named showInstitute() that displays the institute name. Call the same function three times.

PHP Solution

<?php
function showInstitute() {
    echo "VSIT Coding Institute\n";
}

showInstitute();
showInstitute();
showInstitute();
?>

Sample Output

VSIT Coding Institute
VSIT Coding Institute
VSIT Coding Institute

Explanation

You only need to declare a function once. You can call it multiple times whenever you need the same task to execute. This reduces repeated code and makes programs easier to maintain.

Concepts Covered

  • Reusable functions
  • Multiple function calls
  • Code reusability
  • Function declaration

Question 4: Create a Function with One Parameter

Problem Statement

Create a function named greetStudent() that accepts a student’s name as a parameter and displays a personalized greeting.

PHP Solution

<?php
function greetStudent($name) {
    echo "Hello, " . $name . "! Welcome to PHP.";
}

greetStudent("Rahul");
?>

Sample Output

Hello, Rahul! Welcome to PHP.

Explanation

The $name variable is a parameter of the function. When greetStudent("Rahul") is called, the value "Rahul" is passed to the function and stored in $name.

Concepts Covered

  • Function parameters
  • Passing arguments
  • String concatenation
  • Personalized output

Question 5: Create a Function with Multiple Parameters

Problem Statement

Create a function named employeeDetails() that accepts an employee’s name, department, and salary. Display all three details.

PHP Solution

<?php
function employeeDetails($name, $department, $salary) {
    echo "Employee Name: " . $name . "\n";
    echo "Department: " . $department . "\n";
    echo "Salary: Rs. " . $salary . "\n";
}

employeeDetails("Priya", "IT", 35000);
?>

Sample Output

Employee Name: Priya
Department: IT
Salary: Rs. 35000

Explanation

The function accepts three parameters: $name, $department, and $salary. When calling the function, you pass three corresponding arguments in the same order.

Concepts Covered

  • Multiple parameters
  • Passing multiple arguments
  • Function calling
  • Employee data handling

Question 6: Create a Function That Returns a Value

Problem Statement

Create a function named calculateTotal() that accepts two numbers and returns their sum. Display the returned result.

PHP Solution

<?php
function calculateTotal($a, $b) {
    return $a + $b;
}

$result = calculateTotal(100, 200);

echo "Total: " . $result;
?>

Sample Output

Total: 300

Explanation

The return statement sends a value back to the place where the function was called. Here, calculateTotal(100, 200) returns 300, which is stored in the $result variable.

Concepts Covered

  • Return values
  • return statement
  • Function parameters
  • Storing returned results

Question 7: Create a Function to Calculate an Employee’s Annual Salary

Problem Statement

An employee earns ₹30,000 per month. Create a function named annualSalary() that accepts the monthly salary and returns the annual salary.

PHP Solution

<?php
function annualSalary($monthlySalary) {
    return $monthlySalary * 12;
}

$salary = annualSalary(30000);

echo "Annual Salary: Rs. " . $salary;
?>

Sample Output

Annual Salary: Rs. 360000

Explanation

The function accepts the monthly salary as a parameter. It multiplies the amount by 12 and returns the annual salary. You can use the same function for employees with different monthly salaries.

Concepts Covered

  • User-defined functions
  • Parameters and arguments
  • Return values
  • Multiplication
  • Salary calculations

Question 8: Create a Function with a Default Parameter Value

Problem Statement

Create a function named courseDetails() that accepts a course name. Set "PHP" as the default course name. Call the function once with a custom value and once without an argument.

PHP Solution

<?php
function courseDetails($course = "PHP") {
    echo "Selected Course: " . $course . "\n";
}

courseDetails("Python");
courseDetails();
?>

Sample Output

Selected Course: Python
Selected Course: PHP

Explanation

A default parameter value is used when no argument is passed to the function. In the first call, "Python" replaces the default value. In the second call, PHP uses the default value "PHP".

Concepts Covered

  • Default parameters
  • Function arguments
  • Function calling
  • Reusable functions

Question 9: Create a Function to Check Whether a Number Is Even or Odd

Problem Statement

Create a function named checkEvenOdd() that accepts a number and returns "Even" if the number is divisible by 2, otherwise returns "Odd".

PHP Solution

<?php
function checkEvenOdd($number) {
    if ($number % 2 == 0) {
        return "Even";
    } else {
        return "Odd";
    }
}

echo "Number 15: " . checkEvenOdd(15) . "\n";
echo "Number 20: " . checkEvenOdd(20);
?>

Sample Output

Number 15: Odd
Number 20: Even

Explanation

The function receives a number and checks its remainder after division by 2 using the modulus operator %. If the remainder is 0, the function returns "Even". Otherwise, it returns "Odd".

Concepts Covered

  • Function parameters
  • Return values
  • Conditional statements
  • Modulus operator
  • Even and odd numbers

Question 10: Create a Function to Calculate the Final Salary

Problem Statement

Create a function named calculateNetSalary() that accepts basic salary, allowance, and deduction. Calculate and return the employee’s net salary.

Use the following formula:

Net Salary = Basic Salary + Allowance − Deduction

PHP Solution

<?php
function calculateNetSalary($basicSalary, $allowance, $deduction) {
    $netSalary = $basicSalary + $allowance - $deduction;

    return $netSalary;
}

$salary = calculateNetSalary(30000, 5000, 2000);

echo "Net Salary: Rs. " . $salary;
?>

Sample Output

Net Salary: Rs. 33000

Explanation

The function accepts three parameters: basic salary, allowance, and deduction. It adds the allowance to the basic salary, subtracts the deduction, and returns the final amount. This function can be reused for different employee salary calculations.

Concepts Covered

  • User-defined functions
  • Multiple parameters
  • Return statement
  • Arithmetic operations
  • Salary calculation

Key Takeaways

  • A user-defined function is a reusable block of code created by the programmer.
  • Use the function keyword to declare a function in PHP.
  • Call a function using its name followed by parentheses.
  • Parameters allow functions to receive input values.
  • Arguments are the actual values passed when calling a function.
  • Use return to send a result back from a function.
  • Default parameters provide values when arguments are not supplied.
  • A function can be called multiple times after it has been declared.
  • PHP Functions make programs more organized, reusable, and easier to maintain.

Frequently Asked Questions (FAQs)

1. What is a user-defined function in PHP?

A user-defined function is a block of code created by a programmer to perform a particular task. It can be called whenever that task is required.

2. How do you create a function in PHP?

Use the function keyword followed by the function name and parentheses:

function myFunction() {
    echo "Hello PHP";
}

3. How do you call a function in PHP?

Write the function name followed by parentheses:

myFunction();

4. What are parameters in PHP functions?

Parameters are variables written inside a function’s parentheses. They receive values when the function is called.

5. What is the difference between parameters and arguments?

Parameters are variables defined in a function declaration. Arguments are the actual values passed to the function when calling it.

6. What is the purpose of the return statement?

The return statement sends a value from a function back to the calling code. The returned value can be stored in a variable or used in an expression.

7. Can a PHP function accept multiple parameters?

Yes. A function can accept multiple parameters separated by commas.

8. What is a default parameter in PHP?

A default parameter has a predefined value. PHP uses this value when the function is called without an argument for that parameter.

9. Can we call the same function multiple times?

Yes. After declaring a function, you can call it as many times as needed.

10. Why are user-defined functions important in PHP?

They reduce repeated code, improve program organization, make maintenance easier, and allow the same logic to be reused in different parts of an application.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top