PHP Functions

Yo Yogesh.M Updated 17 Oct 2026
7 min read ·Lesson 34 of 102
In this post

What Is a Function? In simple terms: A function is a named, reusable block of code that performs a specific task. You write it once and call it whenever you need that task done — like a recipe you can

What Is a Function?

In simple terms: A function is a named, reusable block of code that performs a specific task. You write it once and call it whenever you need that task done — like a recipe you can follow again and again.

Technically: A function is a unit of code with a name, an optional list of parameters (inputs), a body of statements, and an optional return value (output). Calling the function executes its body with the given arguments and produces a result.

<?php
function formatPrice(float $amount): string
{
    return '₹' . number_format($amount, 2);
}

echo formatPrice(1499.5) . "\n";
echo formatPrice(89) . "\n";

Output

₹1,499.50
₹89.00

Why Functions Matter

BenefitExplanation
ReuseWrite the logic once, use it in many places.
Single point of changeFix a bug or change a rule in one function, and every caller benefits.
ReadabilityA good name (formatPrice()) explains what happens without showing how.
AbstractionCallers do not need to know the details inside.
TestabilityA function with clear inputs and outputs is easy to test in isolation.
Scope isolationVariables inside a function do not interfere with the rest of the program.

Built-in vs User-defined Functions

Built-in Functions

PHP ships with thousands of functions in its core and extensions. You have already used many of them:

<?php
echo strlen("Hello") . "\n";
echo strtoupper("php") . "\n";
echo array_sum([10, 20, 30]) . "\n";
echo max(4, 9, 2) . "\n";
echo date('Y', mktime(0, 0, 0, 1, 1, 2026)) . "\n";

Output

5
PHP
60
9
2026

Built-in functions are always available (as long as the extension providing them is loaded) and are documented in the PHP manual.

User-defined Functions

Functions you write yourself with the function keyword:

<?php
function greet(string $name): string
{
    return "Hello, $name!";
}

echo greet("Meena");

Output

Hello, Meena!

User-defined functions are covered in detail in User-defined Functions.


Anatomy of a Function

function calculateGst(float $amount, float $ratePercent = 18): float
{
    return round($amount * $ratePercent / 100, 2);
}
PartIn the ExamplePurpose
KeywordfunctionStarts the declaration
NamecalculateGstHow the function is called
Parametersfloat $amount, float $ratePercent = 18Inputs, with types and an optional default
Return type: floatThe type of value the function returns
Body{ ... }The statements that run
returnreturn round(...)Sends a value back to the caller

Calling the function:

<?php
function calculateGst(float $amount, float $ratePercent = 18): float
{
    return round($amount * $ratePercent / 100, 2);
}

$gst = calculateGst(2500);
$reducedGst = calculateGst(2500, 5);

echo "GST at 18%: ₹$gst\n";
echo "GST at 5%: ₹$reducedGst\n";

Output

GST at 18%: ₹450
GST at 5%: ₹125
  • calculateGst(2500) uses the default rate of 18.
  • calculateGst(2500, 5) passes a different rate.
  • The returned values are stored in variables and used later.

Parameters and Arguments

The two terms are often mixed up:

  • Parameters are the variables listed in the function definition: $amount, $ratePercent.
  • Arguments are the actual values passed when calling the function: 2500, 5.

PHP offers several ways to pass arguments. Each has its own lesson:

FeatureExampleLesson
Positional argumentscalculateGst(2500, 5)Function Arguments
Default valuesfloat $ratePercent = 18Default Argument Values
Pass by referencefunction addItem(array &$cart)Pass by Reference
Named arguments (PHP 8.0+)calculateGst(amount: 2500, ratePercent: 5)Named Arguments
Variable number of argumentsfunction sum(int ...$numbers)Variadic Functions
Type declarationsfloat $amount, : floatType Declarations in Functions

Returning Values vs Printing

A function should usually return its result rather than print it:

<?php
// Prints directly — can only be used for output
function showTotalBad(array $prices): void
{
    echo "Total: " . array_sum($prices) . "\n";
}

// Returns a value — can be printed, stored, compared, or reused
function total(array $prices): int|float
{
    return array_sum($prices);
}

$cart = [499, 1299, 89];

showTotalBad($cart);

$amount = total($cart);
echo "Total: $amount\n";
echo $amount > 1000 ? "Free shipping\n" : "Shipping charges apply\n";

Output

Total: 1887
Total: 1887
Free shipping

The returning version can be used in calculations, conditions, JSON responses, emails, and tests. The printing version can only print. Return values are covered in Return Values.


Calling a Function Before Its Definition

Functions declared at the top level of a file are available before the line where they are defined, because PHP compiles the whole file before running it:

<?php
echo welcome('Kiran') . "\n";

function welcome(string $name): string
{
    return "Welcome, $name";
}

Output

Welcome, Kiran

This does not apply to functions declared inside an if block or another function — those exist only after the code that declares them has run. For clarity, define functions before use or keep them in separate files that are included first.


Function Names

  • Function names follow the same rules as variable names (letters, digits, underscores; not starting with a digit), but without $.
  • Function names are case-insensitive: formatPrice(), FORMATPRICE(), and FormatPrice() call the same function. Always call a function with the exact case used in its definition for readability.
  • A function name can be declared only once. Declaring it again causes a fatal "Cannot redeclare" error.
  • Use descriptive verbs: calculateTotal(), sendInvoice(), isValidEmail(), formatDate().

Checking Whether a Function Exists

<?php
var_dump(function_exists('strlen'));
var_dump(function_exists('mb_strlen'));
var_dump(function_exists('someUndefinedFunction'));

Output (mb_strlen depends on whether mbstring is installed)

bool(true)
bool(true)
bool(false)

function_exists() is useful for checking optional extensions before using their functions.


Kinds of Functions in PHP

KindExampleLesson
Named (user-defined) functionfunction total(array $p) { ... }User-defined Functions
Recursive functionA function that calls itselfRecursive Functions
Variable function$fn = 'strtoupper'; $fn('php');Variable Functions
Anonymous function$double = function ($n) { return $n * 2; };Anonymous Functions
ClosureAnonymous function capturing variables with useClosures
Arrow function (PHP 7.4+)fn($n) => $n * 2Arrow Functions
First-class callable (PHP 8.1+)strlen(...)First-class Callable Syntax
MethodA function inside a classPHP Methods

Practical Example: Refactoring Repeated Code

Before: Repeated Logic

<?php
$laptop = 54999;
$mouse = 799;

echo "Laptop: ₹" . number_format($laptop * 1.18, 2) . " (incl. GST)\n";
echo "Mouse: ₹" . number_format($mouse * 1.18, 2) . " (incl. GST)\n";

The tax rate and formatting are repeated on every line. Changing the rate or the format means editing every occurrence.

After: One Function

<?php
function priceWithGst(float $price, float $ratePercent = 18): string
{
    $total = $price * (1 + $ratePercent / 100);

    return '₹' . number_format($total, 2) . ' (incl. GST)';
}

$products = ['Laptop' => 54999, 'Mouse' => 799, 'Book' => 450];

foreach ($products as $name => $price) {
    $rate = $name === 'Book' ? 0 : 18;
    echo "$name: " . priceWithGst($price, $rate) . "\n";
}

Output

Laptop: ₹64,898.82 (incl. GST)
Mouse: ₹942.82 (incl. GST)
Book: ₹450.00 (incl. GST)

What Improved

  1. The calculation and format exist in one place.
  2. The rate is a parameter with a sensible default, so special cases (books at 0%) need no new code.
  3. The loop body reads clearly: for each product, print its name and its price with GST.

Common Mistakes

Printing Instead of Returning

Effect: The result cannot be reused or tested.

Fix: Return values; let the caller decide how to display them.

Functions That Do Too Much

Effect: Long functions mixing validation, calculation, database access, and output are hard to change and test.

Fix: Give each function one clear responsibility.

Using Global Variables Inside Functions

Effect: Hidden dependencies and unpredictable behavior.

Fix: Pass data as parameters and return results (see Variables Scope).

Unclear Names

Effect: Names such as doStuff() or process2() force readers to open the function.

Fix: Name functions after what they do or answer.


Best Practices

  • Write small functions that do one thing and are named after that thing.
  • Pass inputs as parameters and return outputs; avoid relying on global state.
  • Declare parameter and return types.
  • Prefer returning values over printing inside functions.
  • Reuse built-in functions instead of re-implementing them.

Official reference: https://www.php.net/manual/en/language.functions.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting
Ask about this post
AI Ask about this post

Ask questions about PHP Functions and get answers drawn from it.

Signed-in readers only.