Functions in PHP
Learn PHP functions — define reusable code, pass parameters, return values, and write maintainable logic for Laravel, WordPress, and REST APIs.
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:
$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:
echo "Welcome, Rahul";
on every page, you can create a function:
function showWelcomeMessage(){echo "Welcome, Rahul";}
Now call it anywhere:
showWelcomeMessage();
If the welcome message changes later, you update it in only one place.
Creating Your First Function
Syntax:
function functionName(){// Code}
Example:
<?phpfunction 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
function
This tells PHP you're creating a function.
2. Function Name
sayHello
Choose descriptive names that explain what the function does.
Good examples:
calculateTotal()sendEmail()getUser()validatePassword()
Avoid vague names like:
test()abc()myFunction()
3. Function Body
Everything inside the braces belongs to the function.
{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:
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:
// Invoice 1// Invoice 2// Invoice 3// Invoice 4
With functions:
generateInvoice();
Call it as many times as needed.
Functions with Parameters
Functions become much more useful when they accept data.
Example:
function greet($name){echo "Welcome " . $name;}greet("Rahul");
Output:
Welcome Rahul
Now try:
greet("Priya");greet("John");
Output:
Welcome Priya Welcome John
The same function works for different users.
Multiple Parameters
Functions can accept multiple inputs.
function add($a, $b){echo $a + $b;}add(10, 20);
Output:
30
Another example:
add(100, 200);
Output:
300
Parameter Order Matters
Consider this function:
function employee($name, $department){echo $name . " works in " . $department;}
Correct:
employee("Rahul", "IT");
Output:
Rahul works in IT
Incorrect:
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:
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:
function square($number){echo $number * $number;}
It prints the result immediately.
Now:
function square($number){return $number * $number;}
You can now:
$result = square(8);echo $result;$total = square(8) + 20;
Returning values provides much greater flexibility.
Real-World Example: Discount Calculator
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
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:
calculateSalary()sendOtp()generateInvoice()findUser()validateEmail()
Avoid names like:
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:
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
function hello(){echo "Hello";}
Nothing happens until you call:
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:
function data()
Good:
function getEmployeeData()
Descriptive names improve readability.
Hands-on Exercise
Create a PHP program that:
- Creates a function to display "Welcome to TechLearningPro".
- Creates a function that accepts a student's name.
- Creates a function to add two numbers.
- Creates a function to calculate GST.
- Creates a function that checks whether a number is even or odd.
- Creates a function that returns the largest of two numbers.
- Creates a function to calculate the area of a rectangle.
- 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.