Functions in PHP

A PHP function is a named block of code with parameters and a return value, and the language treats functions as values in a way that many languages do not. A function name can be stored in a variable, passed as an argument, returned from another function, and combined into a pipeline with array_map or usort. That single design decision is what makes the standard library in PHP feel the way it does: the array functions, the sorting functions and the callback-driven parts of the standard library all accept a function, so your own code plugs into the same machinery. By the end of this chapter you will be able to write a function whose contract is stated in its signature, pass it around as a value, capture state in it safely, and reach for the right built-in function instead of writing a loop you do not need to write.

1. Defining and calling

A function definition names the function, lists its parameters, and declares what it returns.

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

echo greet('Ada');   // Hello, Ada

Function names in PHP are case-insensitive, so greet, Greet and GREET are the same function. It is conventional to use lower case with underscores, and to keep the built-in naming style rather than the mixed style of Java or JavaScript.

A function may be declared before or after it is used, because the whole file is compiled before any of it runs. It also may not be declared inside another function, although it may be declared inside a class, where it becomes a method.

<?php
function outer(): void
{
    // function inner(): void {}   // this is a parse error
}

If a function is called with fewer arguments than it declares, the missing ones take their default values. If it is called with more arguments than it declares, the extras are simply ignored, and you can read them with func_get_args.

<?php
function debug(string $label): void
{
    var_dump(func_get_args());
}

debug('hello', 1, true);   // string(1) "hello", int(1), bool(true)

2. Parameters

Type declarations

Every parameter can carry a type, and the declaration decides what happens when a caller passes something else.

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

The type may be int, float, string, bool, array, object, callable, iterable, mixed, a class name, a union such as int|string, or a nullable type such as ?int.

<?php
function find(int|string $id): string
{
    return is_int($id) ? "#$id" : "slug-$id";
}

A class name in a parameter type is a type hint that both documents and enforces the contract, and it is checked before the body of the function runs.

Default values

A parameter with a default value may be omitted by the caller.

<?php
function connect(string $host, int $port = 3306, string $database = 'app'): string
{
    return "$host:$port/$database";
}

echo connect('localhost');                 // localhost:3306/app
echo connect('localhost', 5432);           // localhost:5432/app

The rule that catches people is that a parameter with a default must come after every parameter without one, unless the later parameters are also given defaults.

<?php
function bad(int $a = 1, int $b): void {}   // parse error

A default value must be a constant expression. It may be a literal, a constant, a class constant, or, since PHP 8.1, the result of a new expression.

Passing by reference

A parameter is passed by value unless it is declared with an ampersand, in which case the caller sees the change.

<?php
function increment(int $value): void
{
    $value++;
}

$n = 1;
increment($n);
echo $n;   // 1, the change stayed inside the function

function incrementByRef(int &$value): void
{
    $value++;
}

incrementByRef($n);
echo $n;   // 2

The argument must be a variable when the parameter is by reference. Passing the result of a function call is a fatal error, because there is no variable to bind to.

<?php
function double(int &$x): void { $x *= 2; }
double(trim('  a  '));   // Cannot pass parameter 1 by reference

By-reference parameters are the right tool for a function that genuinely transforms one of its inputs in place, and the wrong tool for everything else, because they make the caller’s state part of the function’s contract. The alternative is to return the new value.

Variadic parameters

A parameter declared with an ellipsis collects any number of extra arguments into an array.

<?php
function sum(int ...$numbers): int
{
    return array_sum($numbers);
}

echo sum(1, 2, 3);        // 6
echo sum();               // 0

A variadic parameter is always the last one. An array can be spread into it with the spread operator.

<?php
$prices = [10, 20, 30];
echo sum(...$prices);     // 60

Named arguments

Since PHP 8, a caller may pass arguments by name rather than by position.

<?php
echo connect(host: 'localhost', database: 'shop');
// localhost:3306/shop

Named arguments make a call self-documenting, which matters most for functions with several parameters of the same type, or with several boolean flags. The rules are that named arguments come after any positional ones, that the name must match the parameter name exactly, and that an unknown name is an Error.

<?php
connect('localhost', bogus: 1);   // Error: Unknown named parameter $bogus

Named arguments also make it possible to add a parameter to an existing function without breaking every call site, which is one of the strongest arguments for them in a public API.

3. Return values

A function returns nothing unless it says so. return with a value ends the function immediately.

<?php
function firstMatch(array $items, callable $predicate): mixed
{
    foreach ($items as $item) {
        if ($predicate($item)) {
            return $item;
        }
    }
    return null;
}

The return type declaration is optional but should be used.

<?php
function divide(float $a, float $b): float
{
    if ($b === 0.0) {
        throw new DivisionByZeroError('cannot divide by zero');
    }
    return $a / $b;
}

The available return types are void, never, int, float, string, bool, array, object, mixed, a class name, a union of types, and static for a method that returns an instance of the class it was called on.

void means the function returns nothing at all and cannot return a value.

<?php
function record(string $message): void
{
    // write the message somewhere
}

A user-defined function may not have the same name as a built-in one, because redeclaring it is a fatal error.

never, added in PHP 8.1, means the function never returns normally because it always throws or exits.

<?php
function fail(string $reason): never
{
    throw new RuntimeException($reason);
}

never is useful because the type checker then knows that the code after the call is unreachable, and because it documents the intent precisely.

4. Closures and arrow functions

A closure is an anonymous function that can be assigned to a variable.

<?php
$double = function (int $n): int {
    return $n * 2;
};

echo $double(21);   // 42

A closure that needs the surrounding scope uses the use keyword to import variables explicitly. Nothing is captured automatically, which is exactly what you want: the set of captured variables is visible in the source.

<?php
$factor = 3;
$times = function (int $n) use ($factor): int {
    return $n * $factor;
};

echo $times(4);   // 12

The imported variable is a copy, taken when the closure is created. To capture by reference, add an ampersand.

<?php
$factor = 3;
$times = function (int $n) use (&$factor): int {
    return $n * $factor;
};

$factor = 5;
echo $times(4);   // 20, the closure sees the updated value

An arrow function, written fn, is a closure with one expression as its body and with automatic capture by value.

<?php
$factor = 3;
$times = fn (int $n): int => $n * $factor;

echo $times(4);   // 12

The differences are worth remembering. An arrow function captures every variable it uses, by value, at the moment it is created, with no use clause. It returns the value of its single expression, so there is no return keyword. And because the capture is by value, an arrow function can never modify the outer scope.

<?php
$counter = 0;
$increment = fn () => $counter++;   // this does not change $counter

An arrow function is also a single expression, so it cannot contain a statement, a loop or a multi-line body. When you need those, use a closure.

<?php
// A closure, because the body is a statement.
$normalise = function (string $s): string {
    $s = trim($s);
    return strtolower($s);
};

5. Functions as values

PHP treats a function name as a value in several ways.

A variable function is a variable holding a function name.

<?php
$fn = 'strtoupper';
echo $fn('abc');   // ABC

The variable must hold the exact name of a function, or something callable.

A callable is any of five things: a string naming a function, an array holding an object and a method name, an array holding a class name and a static method name, a closure, or an object with an __invoke method.

<?php
class Formatter
{
    public function format(string $value): string
    {
        return strtoupper($value);
    }
}

$callable = [new Formatter(), 'format'];
echo $callable('abc');   // ABC

is_callable tests whether a value can be called, and call_user_func calls it.

<?php
echo call_user_func('strtoupper', 'abc');          // ABC
echo call_user_func([new Formatter(), 'format'], 'abc');   // ABC
echo call_user_func_array('str_replace', ['a', 'b', 'aaa']);   // bbb

Since PHP 8.1 there is a shorter syntax for taking a callable from an existing function: the first-class callable syntax.

<?php
$fn = strlen(...);
echo $fn('hello');   // 5

This produces a closure that calls strlen, and it is the clearest way to hand a function to a higher-order API without a string.

<?php
$lengths = array_map(strlen(...), ['apple', 'fig']);

The double-ellipsis form is how you pass a method of an object.

<?php
$formatter = new Formatter();
$fn = $formatter->format(...);

6. Recursion

A function may call itself, which is the natural way to express a problem defined in terms of a smaller version of itself.

<?php
function factorial(int $n): int
{
    if ($n < 0) {
        throw new InvalidArgumentException('n must not be negative');
    }
    return $n <= 1 ? 1 : $n * factorial($n - 1);
}

echo factorial(5);   // 120

Every recursive function needs a base case that stops the recursion and a step that moves towards it. A recursion without a reachable base case ends in a stack overflow, and a recursion that never gets closer to the base case ends the same way much more slowly.

Recursion is the right tool for problems that are naturally defined recursively, such as walking a directory tree, flattening a nested structure, or parsing a nested expression. It is the wrong tool for a linear scan, where a foreach is clearer and does not risk the stack.

7. Returning by reference

A function can be declared to return by reference, using an ampersand after the function keyword.

<?php
function &getFirst(array &$items): mixed
{
    return $items[0];
}

The caller can then modify the returned value and the change is visible in the original array.

<?php
$items = ['a', 'b'];
$first = &getFirst($items);
$first = 'changed';
var_dump($items);   // changed, b

This mechanism is rarely worth the trouble. It is hard to read, it interacts badly with the ordinary assignment semantics of PHP, and PHP 8.1 deprecated the case where a reference-returning function returns something that is not a reference, which is the kind of accidental reference that produces very confusing bugs. The modern advice is to return arrays and let the caller copy what it needs.

8. The built-in library

PHP ships a large standard library, and knowing the shape of it saves more time than knowing any single function. The categories below are the ones you meet first.

Strings. strlen, strtoupper, tolower, ucfirst, ucwords, trim, ltrim, rtrim, str_repeat, str_pad, substr, strpos, strrpos, str_contains, str_starts_with, str_ends_with, str_replace, substr_replace, explode, implode, sprintf, number_format, nl2br, htmlspecialchars, wordwrap.

<?php
$slug = strtolower(trim(str_replace(' ', '-', 'Hello World')));
// hello-world

Arrays. array_map, array_filter, array_reduce, array_merge, array_slice, array_splice, array_keys, array_values, array_column, array_flip, array_unique, array_combine, array_sum, array_product, in_array, array_search, sort, usort, array_key_exists, array_is_list.

Files. file_get_contents, file_put_contents, file, fopen, fread, fwrite, fclose, file_exists, is_dir, mkdir, unlink, rename, scandir, glob, basename, dirname, pathinfo, realpath.

<?php
$content = file_get_contents(__DIR__ . '/notes.txt');
file_put_contents(__DIR__ . '/copy.txt', $content);

Mathematics. abs, ceil, floor, round, sqrt, pow, intdiv, fmod, max, min, rand, mt_rand, random_int, random_bytes, pi, M_PI, base_convert, number_format.

<?php
echo intdiv(7, 2);      // 3, an integer division
echo round(2.567, 2);  // 2.57

For anything security-sensitive, use random_int rather than rand or mt_rand, because those two are not cryptographically secure.

Dates and times. time, date, mktime, strtotime, checkdate, microtime, and the object-oriented API built on DateTime, DateTimeImmutable, DateInterval and DateTimeZone.

<?php
$now = new DateTimeImmutable('2026-10-22 09:00:00', new DateTimeZone('UTC'));
$later = $now->add(new DateInterval('P2D'));
echo $later->format('Y-m-d H:i');   // 2026-10-24 09:00
echo $now->format('l, F j, Y');     // Thursday, October 22, 2026

DateTimeImmutable is preferred over DateTime because every mutating call on it returns a new object instead of changing the original, which removes a whole category of aliasing bug.

9. Anonymous functions in pipelines

The clearest use of a callback is a transformation written as a pipeline.

<?php
$orders = [
    ['id' => 1, 'customer' => 'Ada',   'total' => 120.50],
    ['id' => 2, 'customer' => 'Grace', 'total' => 89.00],
    ['id' => 3, 'customer' => 'Alan',  'total' => 310.25],
];

$highValue = array_filter($orders, fn (array $o) => $o['total'] > 100);
$totals    = array_map(fn (array $o) => $o['total'], $highValue);
$sum       = array_reduce($totals, fn (float $c, float $t) => $c + $t, 0.0);

The same pattern sorts with a custom rule.

<?php
usort($orders, fn (array $a, array $b) => $b['total'] <=> $a['total']);

And the same pattern groups.

<?php
$byCustomer = [];
foreach ($orders as $order) {
    $byCustomer[$order['customer']][] = $order['id'];
}

A closure is also the natural way to attach behaviour to data without creating a class for it.

<?php
$rules = [
    fn (int $n) => $n > 100,
    fn (int $n) => $n % 2 === 0,
];

$matches = array_filter([1, 2, 101, 102], fn (int $n) => array_any($rules, fn (callable $r) => $r($n)));

array_any and array_all were added in PHP 8.4. On an older version the same test is a short loop over the rules.

<?php
$matches = array_filter([1, 2, 101, 102], function (int $n) use ($rules): bool {
    foreach ($rules as $rule) {
        if ($rule($n)) {
            return true;
        }
    }
    return false;
});

10. Common mistakes

MistakeWhat actually happensCorrection
Passing a function result to a by-reference parameterFatal error, there is no variable to bindAssign it to a variable first
Putting a defaulted parameter before a required oneParse errorReorder the parameters
Using use with a closure that needs nothingNoiseRemove the clause
Expecting an arrow function to modify the outer scopeIt captures by valueUse a closure with use (&$var)
Calling call_user_func with a method name as a plain stringThe method is not foundUse the array form or the first-class callable syntax
Returning by reference for convenienceHard to follow, and deprecated when the return is not a referenceReturn the value and let the caller copy it
Using rand for a token or a passwordIt is predictableUse random_int or random_bytes
Forgetting the base case in a recursive functionStack overflowWrite the base case first, and test it
Using func_get_args in a function with a declared signatureThe extra arguments are still read, but the intent is unclearDeclare the parameters, or accept a variadic

With functions in place, the next chapter takes the state that these functions operate on and gives it a shape: classes that own their data, restrict access to it, and can be extended, reused and tested.

phpfundamentals

Approach:

The subject of this chapter is the function, but the skill being taught is describing an interface that another programmer can rely on. A PHP function has two halves: the signature, which states what the function accepts and what it gives back, and the body, which is an implementation detail. The signature should be complete enough that a caller can use the function without reading its body, which means every parameter carries a type, every return carries a type, and every optional behaviour is expressed either as a default value or as a named argument rather than as a positional flag. The second half of the chapter is the other reason PHP functions are worth a chapter of their own: they are values. A function can be stored, passed, returned and composed, which is what lets your own code plug into the standard library instead of reimplementing it.

Steps:

  1. Write the signature first. Give every parameter a type and every function a return type, and prefer void or never over a bare return; when the function produces nothing or always throws.
  2. Decide the parameter contract deliberately: a default value for optional behaviour, a union or nullable type for a parameter that legitimately accepts more than one shape, and a class name when the parameter is a real collaborator.
  3. Choose pass by value as the default and pass by reference only where the function genuinely transforms the caller’s variable, and remember that a by-reference parameter requires a variable at the call site.
  4. Add a variadic parameter when the number of inputs is genuinely open, and remember that it must come last and can be fed by spreading an array.
  5. Use named arguments at the call site for any function with several parameters of the same type or several boolean flags, since that makes the call readable and makes the function safe to extend.
  6. Choose between a closure and an arrow function on the basis of the body: an expression body means an arrow function, a statement body means a closure, and a closure that needs the outer scope imports it explicitly with use, by value or by reference.
  7. Pass functions around as first-class callables, using the double-ellipsis syntax to obtain one from a named function or a method, so that no string is typed by hand.
  8. Write recursion only for problems that are naturally recursive, always writing the base case first and always moving towards it, and using an ordinary loop for a linear scan.
  9. Avoid returning by reference. Return the value and let the caller decide what to do with it.
  10. Reach for the standard library before writing a loop, and know where to look for it: the string functions, the array functions, the file functions, the mathematics functions and the date and time functions, with random_int for anything security-sensitive and DateTimeImmutable for anything temporal.
  11. Compose your own callbacks with array_map, array_filter, array_reduce and usort, so that a transformation reads as a pipeline rather than as a sequence of intermediate variables.

Answer:

After this chapter, a PHP function can be written down in a way that a reader can use without reading the body.

  • The name says what it does, the parameter types say what it accepts, the default values say what is optional, and the return type says what it produces.
  • Optional behaviour is expressed with a default value and named arguments, never with a positional flag that the caller has to remember the order of.
  • A parameter is passed by value unless the function transforms the caller’s variable, in which case it is passed by reference and the call site passes a variable.
  • A function that returns nothing returns void; a function that always throws returns never; a function that may return one of several types returns a union.
  • A closure is an anonymous function that imports what it needs with use; an arrow function is a closure with an expression body that captures by value automatically.
  • A function used as a value is a callable, obtained most safely with the first-class callable syntax, and called either directly or through call_user_func.
  • A recursive function is written with its base case first, and is used only where the problem is defined recursively.
  • The standard library is searched before a loop is written, and the search has a shape: strings, arrays, files, mathematics, and dates and times.
  • A transformation is written as a pipeline of array_map, array_filter, array_reduce and usort, with the logic expressed as small named closures or arrow functions.

That is the whole of the procedural layer, and it is enough to write the classes of the next chapter, where the same ideas become properties, methods and types that the language enforces for you.

Found an issue with this content?

Tell us what could be improved.