Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

More about functions

Besides parameters and a return value, PHP functions have features that make calls clearer and the functions themselves more flexible.

Named arguments

A call can name the parameter. Then the order of arguments does not matter, and optional parameters can be skipped:

<?php
 
function createUser(string $name, int $age = 18, bool $admin = false)
{
    return $name . ' ' . $age . ' ' . ($admin ? 'admin' : 'user');
}
 
echo createUser(name: 'Anna', admin: true); // Anna 18 admin

Without names you would have to pass the age too, although it does not need changing.

A variable number of arguments

Three dots before a parameter collect all the remaining arguments into an array:

<?php
 
function sum(...$numbers)
{
    return array_sum($numbers);
}
 
echo sum(1, 2, 3), "\n"; // 6
echo sum(10, 20);        // 30

Unpacking an array

The same three dots in a call do the opposite — they spread an array over the arguments:

<?php
 
function volume($width, $height, $depth)
{
    return $width * $height * $depth;
}
 
$box = [2, 3, 4];
 
echo volume(...$box); // 24

Passing by reference

A function normally receives a copy of the value, and the original variable does not change. The & sign before a parameter passes the variable itself:

<?php
 
function addBonus(array &$scores)
{
    foreach ($scores as $key => $score) {
        $scores[$key] = $score + 10;
    }
}
 
$scores = [70, 85];
addBonus($scores);
 
echo implode(', ', $scores); // 80, 95

The built-in sort() and shuffle() work this way. In your own code prefer returning a new value — it is clearer.

Static variables

A regular function variable disappears after the call. A variable with the word static keeps its value between calls:

<?php
 
function nextId()
{
    static $id = 0;
    $id++;
 
    return $id;
}
 
echo nextId(), nextId(), nextId(); // 123

Recursion

A function can call itself. There must be a condition under which the calls stop:

<?php
 
function factorial(int $number): int
{
    if ($number <= 1) {
        return 1;
    }
 
    return $number * factorial($number - 1);
}
 
echo factorial(5); // 120

Recursion suits nested structures: a category tree, folders with files.

Common mistake

Named arguments must come after positional ones. The order cannot be mixed:

<?php
 
function greet(string $greeting, string $name)
{
    return "$greeting, $name!";
}
 
// Wrong: greet(name: 'Anna', 'Hello');
// Fatal error: Cannot use positional argument after named argument
 
echo greet('Hello', name: 'Anna'); // Hello, Anna!

And remember: parameter names become part of the function. Rename a parameter and the calls that use its name break.

Thanks for reading!

Donate to the site — we work hard for you.