Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.

Why functions

Functions bundle reusable logic.

Example

<?php

declare(strict_types=1);

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

echo add(2, 3), "\n";

Parameters and return

Parameters are inputs; return sends a result back. If you declare a return type, return must match it.

Avoid copy-pasting the same block—if you need it twice, try a function.

Exercise

Define add(int $a, int $b): int returning the sum. echo add(4, 5) so the output is 9.

From Zero to PHP — Control flow, functions, arrays, and the web