The best examples of simple PHP function examples for beginners

If you’re just getting started with PHP, nothing builds confidence faster than walking through real, working code. That’s why this guide focuses entirely on **examples of simple PHP function examples for beginners**—short, clear snippets you can copy, tweak, and actually understand. Instead of drowning you in theory, we’ll look at everyday tasks: greeting a user, adding numbers, formatting dates, validating emails, and more. Each example of a PHP function is explained in plain language, with a quick note on when you’d use it in a real project. By the end, you’ll be able to write your own functions instead of pasting random code from the internet and hoping it works. These examples include modern PHP habits that still feel friendly to beginners in 2024–2025: type hints, default values, and cleaner syntax. If you can read basic HTML and echo a string in PHP, you’re ready for this. Let’s open up a `<?php ?>` tag and start building some small but mighty functions.
Written by
Taylor
Published
Updated

Let’s skip the boring definitions and jump straight into examples of simple PHP function examples for beginners. You’ll see the pattern repeat: a function has a name, optional inputs (parameters), and usually an output (a return value).

Here’s the absolute starter example:

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

sayHello(); // outputs: Hello, world!

You define the function once, then call it whenever you need that behavior. That’s the heart of every example of a PHP function you’ll see here.


Example of a PHP function with a parameter

You rarely greet everyone the same way. Let’s personalize it. This is one of the best examples of how parameters make functions more useful:

<?php
function greetUser(string $name) {
    echo "Hello, " . $name . "!";
}

greetUser("Sam");   // Hello, Sam!
greetUser("Taylor"); // Hello, Taylor!

What’s happening:

  • string $name tells PHP that this function expects a string.
  • Inside, we build a message using that name.

Why this matters in real projects:

  • Displaying a logged-in user’s name.
  • Sending personalized emails.
  • Printing names in a report.

This is one of those examples of simple PHP function examples for beginners that you’ll reuse constantly.


Returning values: examples include math and simple logic

Echoing is fine, but in real code you usually want functions to return something so you can use it later.

Adding two numbers

<?php
function addNumbers(int \(a, int \)b): int {
    return \(a + \)b;
}

$result = addNumbers(5, 7);
echo $result; // 12

Here’s what to notice:

  • int \(a, int \)b are typed parameters.
  • : int after the parentheses says, “this function returns an integer.”

This is a classic example of a function that does one small job and does it clearly.

Checking if a number is even

Another clean beginner-friendly example:

<?php
function isEven(int $number): bool {
    return $number % 2 === 0;
}

if (isEven(10)) {
    echo "10 is even";
} else {
    echo "10 is odd";
}

Here the return type is bool (true/false). These examples of simple PHP function examples for beginners show how you can hide small pieces of logic behind a readable function name.


Examples of simple PHP function examples for beginners using default values

Default values keep your code friendly when a parameter is optional.

Greeting with a default name

<?php
function greetWithDefault(string $name = "friend"): string {
    return "Hello, " . $name . "!";
}

echo greetWithDefault();         // Hello, friend!
echo greetWithDefault("Jordan"); // Hello, Jordan!

Why this is one of the best examples for beginners:

  • You see parameters.
  • You see return values.
  • You see a default value.

This pattern appears everywhere: pagination defaults, fallback messages, default filters, and more.


Real examples of string-handling functions

Most web apps manipulate text: usernames, messages, search queries. These real examples of simple PHP function examples for beginners focus on strings.

Making a username URL-friendly (a simple “slug”)

<?php
function slugify(string $text): string {
    \(text = strtolower(\)text);          // convert to lowercase
    \(text = trim(\)text);                // remove spaces at ends
    \(text = preg_replace('/\s+/', '-', \)text); // spaces → dashes
    return $text;
}

echo slugify("My First Blog Post"); // my-first-blog-post

You’d use this when creating URLs like /post/my-first-blog-post.

Shortening long text for previews

<?php
function shortenText(string \(text, int \)limit = 50): string {
    if (strlen(\(text) <= \)limit) {
        return $text;
    }

    return substr(\(text, 0, \)limit) . '...';
}

$preview = shortenText("This is a very long piece of text that should be trimmed.", 30);
echo $preview; // This is a very long piece of...

This example of a function is perfect for article previews, comments, or notification messages.

For a deeper dive into string functions, the official PHP manual is still the gold standard: https://www.php.net/manual/en/ref.strings.php


Date and time: examples include friendly timestamps

Dates can feel intimidating, but they don’t have to. Here are examples of simple PHP function examples for beginners that make timestamps readable.

Formatting a date nicely

<?php
function formatDate(int $timestamp): string {
    return date('F j, Y g:i A', $timestamp);
}

$now = time();
echo formatDate($now); // e.g., March 5, 2025 3:45 PM

This is a real example you’d use for blog posts, logs, or messages.

Showing “time ago” (simple version)

<?php
function timeAgo(int $timestamp): string {
    \(seconds = time() - \)timestamp;

    if ($seconds < 60) {
        return 'Just now';
    }

    \(minutes = floor(\)seconds / 60);
    if ($minutes < 60) {
        return $minutes . ' minute(s) ago';
    }

    \(hours = floor(\)minutes / 60);
    if ($hours < 24) {
        return $hours . ' hour(s) ago';
    }

    \(days = floor(\)hours / 24);
    return $days . ' day(s) ago';
}

echo timeAgo(time() - 90); // 1 minute(s) ago

In 2024–2025, users expect these friendly timestamps everywhere—feeds, chats, notifications—so this is a very practical example of a PHP function.


Input validation: real examples you’ll use in every project

The more PHP is used for logins, forms, and dashboards, the more input validation matters. These real examples of simple PHP function examples for beginners show how to keep things cleaner.

Validating an email address

<?php
function isValidEmail(string $email): bool {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

var_dump(isValidEmail("test@example.com")); // true
var_dump(isValidEmail("not-an-email"));     // false

You’d use this before saving a user or sending a password reset. While not a medical source, you can see similar patterns of input validation and data quality in public data sets from sites like Data.gov: https://www.data.gov/

Sanitizing plain text input

<?php
function sanitizeText(string $text): string {
    return htmlspecialchars(trim($text), ENT_QUOTES, 'UTF-8');
}

$userInput = "  <script>alert('XSS');</script>  ";
echo sanitizeText($userInput);
// outputs: &lt;script&gt;alert(&#039;XSS&#039;);&lt;/script&gt;

This pattern shows up in comment systems, contact forms, and any place where users can type.


Arrays: examples of simple PHP function examples for beginners working with lists

Modern PHP projects rely heavily on arrays: product lists, user IDs, settings. Here are a couple of examples of simple PHP function examples for beginners that work with arrays.

Calculating the average of an array of numbers

<?php
function calculateAverage(array $numbers): float {
    if (count($numbers) === 0) {
        return 0.0;
    }

    \(sum = array_sum(\)numbers);
    return \(sum / count(\)numbers);
}

$scores = [80, 90, 75, 95];
echo calculateAverage($scores); // 85

You might use this for ratings, grades, or analytics dashboards.

Filtering active users from a list

<?php
function getActiveUsers(array $users): array {
    $active = [];

    foreach (\(users as \)user) {
        if (!empty(\(user['active']) && \)user['active'] === true) {
            \(active[] = \)user;
        }
    }

    return $active;
}

$users = [
    ['name' => 'Alex', 'active' => true],
    ['name' => 'Jamie', 'active' => false],
    ['name' => 'Riley', 'active' => true],
];

\(activeUsers = getActiveUsers(\)users);
// returns only Alex and Riley

This is a real example you’d see in admin panels or APIs.

If you’d like to see how arrays show up in data-heavy fields like public health, organizations such as the CDC publish open data sets that often end up as arrays in code: https://data.cdc.gov/


Modern PHP habits in 2024–2025: typing, clarity, and reuse

As of PHP 8.x (the standard in 2024–2025), good code leans heavily on:

  • Type hints (int, string, bool, array, etc.).
  • Clear, descriptive function names.
  • Small, reusable functions instead of giant “do everything” blocks.

Every one of these examples of simple PHP function examples for beginners uses at least one of those habits. That’s on purpose. You’re not just learning syntax; you’re learning patterns that scale when your code grows.

If you want a more structured learning path around these concepts, universities like Harvard offer programming courses that echo the same ideas about small, reusable functions and clean code. Their CS50 material is a classic reference: https://cs50.harvard.edu/


Putting it together: a tiny profile helper

Let’s combine several ideas into one more realistic example of a PHP function that you might actually drop into a project.

<?php
function buildUserProfileSummary(array $user): string {
    \(name   = isset(\)user['name']) ? $user['name'] : 'Unknown user';
    \(email  = isset(\)user['email']) ? $user['email'] : 'No email on file';
    \(joined = isset(\)user['joined']) ? formatDate($user['joined']) : 'Unknown date';

    return "Name: {\(name}\nEmail: {\)email}\nJoined: {$joined}";
}

function formatDate(int $timestamp): string {
    return date('F j, Y', $timestamp);
}

$user = [
    'name'  => 'Jordan Lee',
    'email' => 'jordan@example.com',
    'joined'=> strtotime('2024-06-01'),
];

echo nl2br(buildUserProfileSummary($user));

Here you see:

  • An array parameter.
  • Reuse of another function (formatDate).
  • Simple defaults when data is missing.

It’s still beginner-friendly, but it feels like something from a real codebase.


FAQ: examples of common beginner questions about PHP functions

What are some basic examples of PHP functions I should learn first?

Start with small, focused tasks. The best examples for beginners include:

  • A greeting function that takes a name.
  • A math function like addNumbers().
  • A boolean function such as isEven().
  • A string helper like shortenText().
  • A date formatter like formatDate().

These examples of simple PHP function examples for beginners show all the main ideas you’ll use later: parameters, return values, and simple logic.

Can you give an example of a PHP function that combines validation and formatting?

Yes. A very practical example of this is a function that checks an email and returns a cleaned-up version or null if it’s not valid:

<?php
function validateAndNormalizeEmail(string $email): ?string {
    \(email = trim(strtolower(\)email));

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return null;
    }

    return $email;
}

This single function both validates and normalizes user input.

How many lines should a simple PHP function have for beginners?

There’s no hard rule, but most examples of simple PHP function examples for beginners work best when they’re short—often 3 to 15 lines. Short functions are easier to read, test, and reuse. If your function starts scrolling off the screen, it might be time to split it into smaller pieces.

Are these examples still good for PHP in 2024–2025?

Yes. The examples here use modern PHP 8 features like type hints and return types, which are standard in 2024–2025. If you keep following these patterns, your beginner code will age well as you move into frameworks like Laravel or Symfony.


By walking through these examples of simple PHP function examples for beginners, you’ve seen how to:

  • Define functions with and without parameters.
  • Return different types of values.
  • Work with strings, numbers, dates, and arrays.
  • Write code that feels small, readable, and reusable.

From here, the next step is simple: keep writing your own small functions, one focused task at a time. That’s how real PHP developers sharpen their skills.

Explore More PHP Code Snippets

Discover more examples and insights in this category.

View All PHP Code Snippets