PHP Mastery Tutorial 0/120 lessons ~6 min read Lesson 18

    Functions in PHP

    Learn PHP functions — define reusable code, pass parameters, return values, and write maintainable logic for Laravel, WordPress, and REST APIs.

    Course progress0%
    Focus
    22 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Functions in PHP

    Introduction

    Imagine you're building an e-commerce website.

    You need to calculate the total price of a shopping cart.

    You write this code:

    php
    $total = $price + ($price * 18 / 100);
    echo $total;

    Later, you need the same calculation on another page.

    You copy the code again.

    A few days later, you need it on five more pages.

    Now imagine the tax rate changes from 18% to 20%.

    You have to find every copied block and update it.

    This approach is time-consuming, error-prone, and difficult to maintain.

    There is a better solution.

    Functions.

    A function allows you to write a block of code once and use it many times.

    Instead of duplicating logic, you simply call the function whenever you need it.

    Professional PHP developers rely heavily on functions because they make applications:

    • Easier to maintain
    • Easier to test
    • Easier to debug
    • More reusable
    • More organized

    Whether you're building a Laravel application, WordPress plugin, REST API, or enterprise software, functions are everywhere.

    In this lesson, you'll learn how to create your own functions, pass data into them, return values, and write clean, reusable PHP code.

    What is a Function?

    A function is a named block of reusable code that performs a specific task.

    Think of a function as a machine.

    • You give it some input.
    • It performs a task.
    • It optionally returns a result.

    Instead of rewriting the same logic repeatedly, you define the function once and call it whenever needed.

    Why Do We Use Functions?

    Without functions:

    • Code becomes repetitive.
    • Bugs are harder to fix.
    • Maintenance takes longer.
    • Applications become difficult to understand.

    With functions:

    • Write once, reuse many times.
    • Improve readability.
    • Reduce duplication.
    • Make testing easier.
    • Encourage modular design.

    One of the core software engineering principles is DRY (Don't Repeat Yourself). Functions help you follow this principle by keeping reusable logic in one place.

    Real-World Example

    Imagine an online shopping website.

    Every page displays the logged-in user's name.

    Instead of writing:

    php
    echo "Welcome, Rahul";

    on every page, you can create a function:

    php
    function showWelcomeMessage()
    {
    echo "Welcome, Rahul";
    }

    Now call it anywhere:

    php
    showWelcomeMessage();

    If the welcome message changes later, you update it in only one place.

    Creating Your First Function

    Syntax:

    php
    function functionName()
    {
    // Code
    }

    Example:

    php
    <?php
    function sayHello()
    {
    echo "Hello PHP!";
    }
    sayHello();

    Output:

    Hello PHP!

    The function is defined once and executed when it is called.

    Understanding the Parts of a Function

    A function has three important parts:

    1. Function Keyword

    php
    function

    This tells PHP you're creating a function.

    2. Function Name

    php
    sayHello

    Choose descriptive names that explain what the function does.

    Good examples:

    php
    calculateTotal()
    sendEmail()
    getUser()
    validatePassword()

    Avoid vague names like:

    php
    test()
    abc()
    myFunction()

    3. Function Body

    Everything inside the braces belongs to the function.

    php
    {
    echo "Hello";
    }

    This code executes only when the function is called.

    Calling a Function

    Defining a function does not execute it.

    You must call it.

    Example:

    php
    function greet()
    {
    echo "Welcome!";
    }
    greet();
    greet();
    greet();

    Output:

    Welcome!
    Welcome!
    Welcome!

    One function definition. Three executions.

    Why This is Powerful

    Imagine sending invoices.

    Without functions:

    php
    // Invoice 1
    // Invoice 2
    // Invoice 3
    // Invoice 4

    With functions:

    php
    generateInvoice();

    Call it as many times as needed.

    Functions with Parameters

    Functions become much more useful when they accept data.

    Example:

    php
    function greet($name)
    {
    echo "Welcome " . $name;
    }
    greet("Rahul");

    Output:

    Welcome Rahul

    Now try:

    php
    greet("Priya");
    greet("John");

    Output:

    Welcome Priya
    Welcome John

    The same function works for different users.

    Multiple Parameters

    Functions can accept multiple inputs.

    php
    function add($a, $b)
    {
    echo $a + $b;
    }
    add(10, 20);

    Output:

    30

    Another example:

    php
    add(100, 200);

    Output:

    300

    Parameter Order Matters

    Consider this function:

    php
    function employee($name, $department)
    {
    echo $name . " works in " . $department;
    }

    Correct:

    php
    employee("Rahul", "IT");

    Output:

    Rahul works in IT

    Incorrect:

    php
    employee("IT", "Rahul");

    Output:

    IT works in Rahul

    Always pass arguments in the correct order.

    Returning Values

    Professional developers usually return values instead of printing them directly.

    Example:

    php
    function multiply($a, $b)
    {
    return $a * $b;
    }
    $result = multiply(5, 6);
    echo $result;

    Output:

    30

    Returning values makes functions reusable because the caller decides what to do with the result.

    echo vs return

    Consider this function:

    php
    function square($number)
    {
    echo $number * $number;
    }

    It prints the result immediately.

    Now:

    php
    function square($number)
    {
    return $number * $number;
    }

    You can now:

    php
    $result = square(8);
    echo $result;
    $total = square(8) + 20;

    Returning values provides much greater flexibility.

    Real-World Example: Discount Calculator

    php
    function calculateDiscount($price, $discountPercentage)
    {
    $discount = ($price * $discountPercentage) / 100;
    return $price - $discount;
    }
    echo calculateDiscount(1000, 20);

    Output:

    800

    This function can now be reused across your application.

    Real-World Example: Student Result

    php
    function isPassed($marks)
    {
    return $marks >= 35;
    }
    if (isPassed(80)) {
    echo "Pass";
    } else {
    echo "Fail";
    }

    Output:

    Pass

    Returning a boolean is a common practice in validation functions.

    Function Naming Best Practices

    Choose names that describe what the function does.

    Good examples:

    php
    calculateSalary()
    sendOtp()
    generateInvoice()
    findUser()
    validateEmail()

    Avoid names like:

    php
    data()
    value()
    temp()
    abc()

    Good names make your code self-explanatory.

    Best Practices

    Write Small Functions

    A function should perform one task.

    Instead of creating one large function that handles login, validation, email, and database updates, split those responsibilities into smaller functions.

    Use Meaningful Names

    Function names should read like actions.

    Examples:

    php
    calculateTax()
    sendNotification()
    createUser()

    Return Values When Appropriate

    Whenever possible, return results instead of printing them directly. This makes the function reusable in different contexts.

    Avoid Code Duplication

    If you copy the same code into multiple places, consider moving it into a function.

    Keep Functions Focused

    A function should solve one problem.

    If it becomes too large, divide it into smaller functions.

    Common Mistakes

    Forgetting to Call the Function

    php
    function hello()
    {
    echo "Hello";
    }

    Nothing happens until you call:

    php
    hello();

    Mixing Too Many Responsibilities

    Avoid writing functions that perform unrelated tasks.

    Bad example: processOrder() that:

    • Sends emails
    • Calculates taxes
    • Updates inventory
    • Generates invoices

    Break these into smaller functions.

    Using echo When You Need return

    Printing inside the function limits its reuse.

    Returning the value gives the caller more flexibility.

    Poor Naming

    Bad:

    php
    function data()

    Good:

    php
    function getEmployeeData()

    Descriptive names improve readability.

    Hands-on Exercise

    Create a PHP program that:

    1. Creates a function to display "Welcome to TechLearningPro".
    2. Creates a function that accepts a student's name.
    3. Creates a function to add two numbers.
    4. Creates a function to calculate GST.
    5. Creates a function that checks whether a number is even or odd.
    6. Creates a function that returns the largest of two numbers.
    7. Creates a function to calculate the area of a rectangle.
    8. Calls each function with different values and displays the results.

    Try implementing these functions yourself before checking any reference solutions.

    Summary

    Functions are one of the most important building blocks in PHP.

    They allow you to organize your code into small, reusable units that perform specific tasks.

    By using functions, you can eliminate duplication, improve readability, simplify testing, and build applications that are easier to maintain.

    Professional PHP developers create functions for everything from validation and calculations to database operations and API integrations.

    Key Takeaways

    • A function is a reusable block of code.
    • Define a function once and call it whenever needed.
    • Functions can accept parameters.
    • Parameters allow the same function to work with different data.
    • Use return to send results back to the caller.
    • Prefer descriptive function names.
    • Keep functions small and focused on a single responsibility.
    • Reusable functions lead to cleaner and more maintainable applications.

    What's Next?

    In Default Parameters, Named Arguments & Variable Scope, you'll learn default parameter values, PHP 8 named arguments, local and global scope, and the global keyword.

    Continue at /learn/php/functions-part-2.

    Ready to mark this lesson complete?Track your journey across the entire course.