MasterPHP.in
PHP Tutorial

Functions in PHP


As your PHP applications grow, writing the same code repeatedly becomes inefficient and hard to maintain. Functions help you solve this by allowing you to group reusable logic into a single block that can be called whenever needed.

In this lesson, you’ll learn how to create custom functions in PHP, pass parameters to them, and return values. By the end, you’ll be able to write modular and reusable code.


What is a Function in PHP?

A function is a block of code that performs a specific task and can be reused multiple times throughout your program.

Instead of repeating logic, you define it once and call it whenever required.


Creating a Custom Function

Syntax

function functionName() {
    // code to execute
}

Example

function greet() {
    echo "Welcome to MasterPHP";
}

greet();

Output:

Welcome to MasterPHP

Use case:

Useful for reusable actions like printing messages, formatting output, or performing repeated tasks.


Functions with Parameters

Parameters allow you to pass data into a function, making it more flexible.

Example

function greetUser($name) {
    echo "Hello " . $name;
}

greetUser("Rohan");

Output:

Hello Rohan

Use case:

Used when you want the function to behave differently based on input values.


Multiple Parameters

You can pass more than one value into a function.

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

add(10, 5);

Output:

15


Default Parameters

You can assign default values to parameters. If no value is passed, the default is used.

function greetUser($name = "Guest") {
    echo "Hello " . $name;
}

greetUser();

Output:

Hello Guest


Returning Values from Functions

Instead of printing output directly, functions can return values using the return keyword.

Example

function add($a, $b) {
    return $a + $b;
}

$result = add(10, 5);
echo $result;

Output:

15

Why use return:

Returning values allows you to reuse the result in other parts of your program instead of just displaying it.


Difference Between echo and return

Feature | echo                | return
------- | ------------------- | -------------------------
Purpose | Outputs directly    | Sends value back
Usage   | Immediate display   | Reusable in code
Flow    | Continues execution | Ends function execution


Variable Scope in PHP

Variables defined inside a function are not accessible outside it, and variables defined outside are not automatically available inside the function.

Example

$globalVar = "Hello";

function test() {
    echo $globalVar; // Undefined
}

test();

Why it fails:

The function cannot access variables defined outside its scope.

Fix using global

$globalVar = "Hello";

function test() {
    global $globalVar;
    echo $globalVar;
}

test();

Output:

Hello

Key takeaway:

Variables inside functions are local by default. Use global only when necessary.


Common Mistakes Beginners Make

1. Passing Arguments in Wrong Order

function subtract($a, $b) {
    return $a - $b;
}

echo subtract(5, 10); // Output: -5

Why it’s confusing:

The order of arguments matters, and swapping them changes the result.

2. Missing Parameters

function greetUser($name) {
    echo "Hello " . $name;
}

greetUser();

Why it fails:

No argument is passed, which can cause errors.

3. Using echo Instead of return

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

Why it’s limiting:

You cannot reuse the result in further calculations.

4. Code After return Not Executed

function test() {
    return "Done";
    echo "Hello";
}

Why it fails:

Any code after return will not run.


Real-World Example

function calculateTotal($price, $tax) {
    $total = $price + $tax;
    return $total;
}

$totalAmount = calculateTotal(100, 18);

echo "Total Amount: ₹" . $totalAmount;

Output:

Total Amount: ₹118


Practice Exercise

Task 1

Create a function that prints your name.

Expected Output:

Rohan

Task 2

Create a function that adds two numbers using parameters.

Expected Output:

15

Task 3

Create a function multiply that takes two numbers and returns their product. Call it with 5 and 10.

Expected Output:

50


Summary

In this lesson, you learned how to create custom functions in PHP, pass parameters, and return values. You also learned about variable scope, which is essential for understanding how data behaves inside and outside functions.

Functions are a core building block for writing clean, reusable, and maintainable code.

Share this tutorial