Skip to content
AgileLogics
5 min read

Functions

Prerequisites: Array functions

Functions are declared with function. Since PHP 7, you can (and should) declare parameter and return types.

Syntax

function greet(string $name): string
{
    return "Hello, $name!";
}

Example

function square(int $n): int
{
    return $n * $n;
}

echo square(4);

Expected output

16

Parameters can have default values, and PHP 8 added named arguments so you can pass them out of order by name:

function makeUser(string $name, string $role = 'member'): array
{
    return ['name' => $name, 'role' => $role];
}

makeUser(name: 'Ada', role: 'admin');

Practice

Write a function isEven(int $n): bool that returns true if $n is even.

Show solution
function isEven(int $n): bool
{
    return $n % 2 === 0;
}