PHP Functions

PHP functions are reusable blocks of code with a name. PHP includes thousands of built-in functions, and you can write your own to keep code organised and avoid repetition.

Creating a Function

Declare a function with the function keyword, give it parameters, and use return to send a value back. Type declarations document and enforce what goes in and out.

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

Default Values and Named Arguments

Parameters can have defaults. Since PHP 8 you can pass arguments by name, which makes calls clearer and lets you skip optional ones.

<?php
function price(float $amount, float $tax = 0.17, bool $round = true): float {
    $total = $amount * (1 + $tax);
    return $round ? round($total, 2) : $total;
}
echo price(100), "\n";
echo price(100, round: false, tax: 0.05);
117
105

Nullable and Union Types

?string means "string or null". int|float is a union type accepting either.

<?php
function findUser(int $id): ?string {
    return $id === 1 ? "Admin" : null;
}
function format(int|float $n): string {
    return number_format($n, 1);
}
var_dump(findUser(2));
echo format(3), " ", format(2.75);
NULL
3.0 2.8

Variadic Functions

The ... operator collects any number of arguments into an array.

<?php
function sum(int ...$numbers): int {
    return array_sum($numbers);
}
echo sum(1, 2, 3, 4);
10

Anonymous and Arrow Functions

Closures are functions without a name, often passed to array functions. Arrow functions (fn) are short one-expression closures that automatically capture outer variables.

<?php
$rate = 2;
$double = function (int $x) use ($rate) {
    return $x * $rate;
};
$triple = fn($x) => $x * 3;

echo $double(5), " ", $triple(5), "\n";
echo implode(",", array_map(fn($n) => $n * $rate, [1, 2, 3]));
10 15
2,4,6

Passing by Reference

Normally a function receives a copy of a value. Prefix a parameter with & to modify the caller variable directly. Use this sparingly; returning a value is usually clearer.

Frequently asked questions

How do I return multiple values from a PHP function?

Return an array and destructure it: [$min, $max] = stats($data);. For more structure, return an object.

What are named arguments in PHP?

A PHP 8 feature that lets you pass arguments by parameter name, like price(100, tax: 0.05), in any order.

What is the difference between a closure and an arrow function?

A closure needs use() to capture outer variables and can contain many statements. An arrow function captures automatically but holds a single expression.