PHP Functions Explained (How to Create and Use Functions with Examples)

Introduction

PHP functions allow you to group reusable code into a single block. Instead of writing the same code multiple times, you can define a function once and reuse it whenever needed.

In this guide, you’ll learn how to create and use PHP functions with examples, including parameters, return values, and real-world use cases.

🎯 What You’ll Learn

  • What PHP functions are and why they are used
  • How to create and call functions in PHP
  • Using parameters and return values
  • Difference between built-in and user-defined functions
  • Real-life examples and best practices

What is a Function in PHP? (Beginner Explanation)

A function is a block of code that:

  • Performs a specific task
  • Can accept input (parameters)
  • Can return a value

Once defined, a function can be called anywhere in the script.

How to Create a Function in PHP

Syntax

function functionName() {
    // code to execute
}

Example

function sayHello() {
    echo "Hello, PHP!";
}

sayHello();

Output:

Hello, PHP!

PHP Function with Parameters (Example)

Parameters allow you to pass values into a function.

Example

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

greetUser("Divyesh");

Output:

Welcome, Divyesh

PHP Function with Multiple Parameters

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

addNumbers(10, 20);

Output:

30

PHP Function Return Value (With Example)

Functions can return values using the return keyword.

function multiply($x, $y) {
    return $x * $y;
}

$result = multiply(4, 5);
echo $result;

Output:

20

Default Parameters in PHP Functions

You can set default values for parameters.

function setLanguage($lang = "PHP") {
    echo "Language: " . $lang;
}

setLanguage();
setLanguage("WordPress");

Function with Conditional Logic

function checkAge($age) {
    if ($age >= 18) {
        return "Adult";
    } else {
        return "Minor";
    }
}

echo checkAge(20);

Types of Functions in PHP

  • Built-in
  • User-defined

Built-in Functions

PHP provides many built-in functions, such as:

  • strlen()
  • count()
  • date()
  • strpos()

Example:

echo strlen("Hello PHP");

User-Defined Functions

Functions created by developers to perform custom tasks.

Common PHP Built-in Functions with Examples

PHP provides many built-in functions to work with strings. These are used constantly when handling user input, form data, and content.

1️⃣ strlen() – Get String Length

<?php
$text = "Hello PHP";
echo strlen($text); // 9
?>

Use case:
Check password length or input validation.

2️⃣ strtolower() and strtoupper() – Change Case

<?php
$name = "DivPHP Tutorials";echo strtolower($name); // divphp tutorials  
echo strtoupper($name); // DIVPHP TUTORIALS
?>

Use case:
Normalize user input before comparison.

3️⃣ trim() – Remove Extra Spaces

<?php
$input = "   hello world   ";
echo trim($input); // "hello world"
?>

Use case:
Clean form inputs before saving to database.

4️⃣ substr() – Get Part of a String

<?php
$message = "Welcome to DivPHP Tutorials";
echo substr($message, 0, 7); // Welcome
?>

Use case:
Show short previews or excerpts.

5️⃣ str_replace() – Replace Text

<?php
$text = "I love Java";
echo str_replace("Java", "PHP", $text); // I love PHP
?>

Use case:
Replace words or sanitize content.

6️⃣ Real-World Example (Cleaning User Input)

<?php
$username = "  DivUser  ";
$cleanUsername = strtolower(trim($username));
echo $cleanUsername; // divuser
?>

This example combines multiple functions into a simple real-world use case.

🔄 When to Use PHP Functions

  • When code is repeated multiple times
  • When performing a specific task
  • When organizing large programs
  • When improving readability

Best Practices for PHP Functions

  • Use meaningful function names
  • Keep functions small and focused
  • Avoid using global variables inside functions
  • Return values instead of echoing when possible

💡 Real-Life Example of PHP Functions

Functions are widely used in real applications like e-commerce websites and WordPress development.

function formatPrice($price) {
    return "₹" . number_format($price, 2);
}

echo formatPrice(1500);

This type of function is commonly used in:

  • E-commerce websites
  • WordPress themes and plugins

Real-World Example: PHP Functions in WordPress

In WordPress development, functions are used to display dynamic content and handle data.

When building themes or plugins in WordPress, you’ll frequently use built-in functions to display content and manage data. These are real examples of how PHP functions are used in practical projects.

1️⃣ get_the_title() – Get Post Title

<?php
echo get_the_title();
?>

Use case:
Display the current post title inside a theme template.

2️⃣ the_content() – Display Post Content

<?php
the_content();
?>

Use case:
Output the main content of a post or page.

3️⃣ wp_get_current_user() – Get Logged-in User

<?php
$current_user = wp_get_current_user()

;if ( $current_user->exists() ) {
    echo "Hello, " . esc_html( $current_user->display_name );
} else {
    echo "Hello, Guest!";
}
?>

Use case:
Show personalized greetings in dashboards or headers.

4️⃣ wp_redirect() – Redirect Users

<?php
wp_redirect( home_url() );
exit;
?>

Use case:
Redirect users after form submission or login.

Practice Tasks (Try It Yourself)

Practice these tasks to strengthen your understanding of PHP functions.

🧪 Task 1: Create a Greeting Function

Create a function called welcomeUser() that accepts a name and prints:

Welcome, Name!

Hint: Use a parameter and echo.

🧮 Task 2: Simple Calculator Function

Create a function multiply() that takes two numbers and returns their multiplication result.

Hint: Use return and call the function with different values.

🧹 Task 3: Clean User Input

Create a function cleanInput() that:

  • Removes extra spaces
  • Converts text to lowercase

Hint: Use trim() and strtolower() inside your function.

🔁 Task 4 (Optional): Call a Function Inside Another Function

Create two functions:

  • getPrice() – returns a number
  • formatPrice() – formats the price and displays it

Call getPrice() inside formatPrice().

✅ Challenge (Optional)

Create a function that checks if a number is even or odd and prints the result.

Summary

PHP functions help you write cleaner and reusable code by organizing logic into reusable blocks. In this tutorial, you learned how to:

  • Create and call functions
  • Use parameters and return values
  • Work with built-in and user-defined functions

Functions are essential for building scalable PHP applications and are widely used in real-world projects like WordPress development.

👉 Next, learn how to work with PHP Arrays to manage multiple values efficiently.

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *