PHP Functions
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
| Benefit | Explanation |
|---|---|
| Reuse | Write the logic once, use it in many places. |
| Single point of change | Fix a bug or change a rule in one function, and every caller benefits. |
| Readability | A good name (formatPrice()) explains what happens without showing how. |
| Abstraction | Callers do not need to know the details inside. |
| Testability | A function with clear inputs and outputs is easy to test in isolation. |
| Scope isolation | Variables 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);
}
| Part | In the Example | Purpose |
|---|---|---|
| Keyword | function | Starts the declaration |
| Name | calculateGst | How the function is called |
| Parameters | float $amount, float $ratePercent = 18 | Inputs, with types and an optional default |
| Return type | : float | The type of value the function returns |
| Body | { ... } | The statements that run |
return | return 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:
| Feature | Example | Lesson |
|---|---|---|
| Positional arguments | calculateGst(2500, 5) | Function Arguments |
| Default values | float $ratePercent = 18 | Default Argument Values |
| Pass by reference | function addItem(array &$cart) | Pass by Reference |
| Named arguments (PHP 8.0+) | calculateGst(amount: 2500, ratePercent: 5) | Named Arguments |
| Variable number of arguments | function sum(int ...$numbers) | Variadic Functions |
| Type declarations | float $amount, : float | Type 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(), andFormatPrice()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
| Kind | Example | Lesson |
|---|---|---|
| Named (user-defined) function | function total(array $p) { ... } | User-defined Functions |
| Recursive function | A function that calls itself | Recursive Functions |
| Variable function | $fn = 'strtoupper'; $fn('php'); | Variable Functions |
| Anonymous function | $double = function ($n) { return $n * 2; }; | Anonymous Functions |
| Closure | Anonymous function capturing variables with use | Closures |
| Arrow function (PHP 7.4+) | fn($n) => $n * 2 | Arrow Functions |
| First-class callable (PHP 8.1+) | strlen(...) | First-class Callable Syntax |
| Method | A function inside a class | PHP 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
- The calculation and format exist in one place.
- The rate is a parameter with a sensible default, so special cases (books at 0%) need no new code.
- 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