PHP Functions
A function is a named block of code that you can run whenever you need it. PHP ships with thousands of built-in functions (strlen(), count(), date()...), and you can write your own to avoid repeating code and to give a meaningful name to a piece of logic.
Defining and calling a function
Declare a function with the function keyword, a name, a parameter list in parentheses and a body in braces. Call it by writing its name followed by ().
<?php
function greet(string $name): string {
return "Hello, $name!";
}
echo greet("Linh"), "\n";
echo greet("Carlos"), "\n";
// Function names are case-insensitive, but always use the declared spelling
echo strlen(greet("Ana")), " characters\n";Hello, Linh!
Hello, Carlos!
11 characters
return sends a value back to the caller and ends the function immediately. A function without return (or with a bare return;) returns null. Functions declared at the top level can be called even before their definition in the file.
Type declarations
PHP lets you declare the type of each parameter and of the return value. They document your intent and PHP checks them at runtime.
| Declaration | Meaning |
|---|---|
int, float, string, bool, array |
scalar and array types |
?string |
a string or null |
int|float |
union type: either one |
mixed |
anything |
: void |
the function returns nothing |
: never |
the function never returns (always throws or exits) |
Default values and named arguments
A parameter with a default value becomes optional. Since PHP 8.0 you can also pass arguments by name, which lets you skip optional ones and makes calls self-explanatory.
<?php
function formatPrice(float $amount, string $currency = "USD", int $decimals = 2): string {
return number_format($amount, $decimals) . " " . $currency;
}
echo formatPrice(1234.5), "\n";
echo formatPrice(1234.5, "EUR"), "\n";
echo formatPrice(1234.5, decimals: 0), "\n";
echo formatPrice(currency: "VND", amount: 250000, decimals: 0), "\n";1,234.50 USD
1,234.50 EUR
1,235 USD
250,000 VND
Variadic functions
A parameter written as ...$name collects any number of remaining arguments into an array. The same ... spreads an array into separate arguments at the call site.
<?php
function average(string $label, float ...$numbers): string {
if (count($numbers) === 0) {
return "$label: no data";
}
$avg = array_sum($numbers) / count($numbers);
return sprintf("%s: %.2f (from %d values)", $label, $avg, count($numbers));
}
echo average("Monday", 20, 22, 25), "\n";
echo average("Tuesday"), "\n";
$week = [18.5, 19.0, 21.5, 23.0];
echo average("Week", ...$week), "\n";Monday: 22.33 (from 3 values)
Tuesday: no data
Week: 20.50 (from 4 values)
Passing by reference
Arguments are normally passed by value: the function gets a copy, and changes inside it don't affect the caller. Prefix the parameter with & to pass by reference, so the function works on the caller's variable directly. Built-ins like sort() work this way.
<?php
function addBonusCopy(int $points): void {
$points += 100;
}
function addBonus(int &$points): void {
$points += 100;
}
$score = 50;
addBonusCopy($score);
echo "After addBonusCopy: $score\n";
addBonus($score);
echo "After addBonus: $score\n";This prints:
After addBonusCopy: 50
After addBonus: 150Tip: Returning a new value is usually clearer than modifying a reference. Use references sparingly.
Recursion
A function may call itself. Every recursive function needs a base case that stops the chain of calls.
<?php
function factorial(int $n): int {
if ($n <= 1) {
return 1; // base case
}
return $n * factorial($n - 1);
}
function sumDigits(int $n): int {
return $n < 10 ? $n : ($n % 10) + sumDigits(intdiv($n, 10));
}
echo "5! = ", factorial(5), "\n";
echo "10! = ", factorial(10), "\n";
echo "Digit sum of 98765 = ", sumDigits(98765), "\n";5! = 120
10! = 3628800
Digit sum of 98765 = 35
Strict types
By default PHP is forgiving with scalar types: passing the string "5" to an int parameter silently converts it. Adding declare(strict_types=1); as the very first statement of a file turns this off for calls made from that file — a wrong type throws a TypeError instead.
<?php
declare(strict_types=1);
function double(int $n): int {
return $n * 2;
}
echo double(21), "\n";
try {
echo double("21"), "\n";
} catch (TypeError $e) {
// The message also mentions the file and line; keep only the first part
$msg = explode(", called in", $e->getMessage())[0];
echo "TypeError: $msg\n";
}42
TypeError: double(): Argument #1 ($n) must be of type int, string given
Without the declare line, double("21") would simply return 42. Many modern projects enable strict types in every file.
Variable scope in brief
Variables created inside a function are local: they don't exist outside it, and the function can't see variables from the outside unless they are passed in as arguments. The Variables Scope lesson covers global and static in detail.
Test yourself
What does a function return if it has no return statement?
0falsenull- An empty string
Given function f(int $a, int $b = 2, int $c = 3), which call sets only $c to 9?
f(1, , 9)f(1, c: 9)f(c = 9, 1)f(1, $c => 9)
What does & in function inc(int &$x) mean?
$xis optional$xis passed by reference, so changes affect the caller's variable$xmust be a constant$xcollects extra arguments