Functions

A PHP function is declared with the function keyword, can take default values for parameters you don't always want to specify, and — since PHP 7 — can optionally declare the types it expects in and the type it hands back.

Declaring and calling a function

PHP functions.php
<?php
function add($a, $b) {
    return $a + $b;
}

echo add(3, 4);
?>
Output
7

Parameters, unlike variables elsewhere in PHP, need no = to be introduced — they're just named in the parentheses, and whatever's passed to the call gets bound to them for the duration of the function.

Default parameter values

A parameter can specify a fallback value, used whenever the caller doesn't supply one:

PHP defaults.php
<?php
function greet($name, $greeting = "Hello") {
    return "$greeting, $name!";
}

echo greet("Sam") . "\n";
echo greet("Priya", "Welcome");
?>
Output
Hello, Sam!
Welcome, Priya!

Parameters with defaults must come after any without one — function greet($greeting = "Hello", $name) would be a syntax error, since PHP wouldn't know which arguments line up with which parameters when only one is given.

Type declarations and return types

Function signatures can optionally declare the type of each parameter and the return value. PHP still enforces this at runtime — it's not just documentation:

PHP types.php
<?php
function multiply(int $a, int $b): int {
    return $a * $b;
}

echo multiply(6, 7) . "\n";
echo multiply("6", "7");
?>
Output
42
42

int $a, int $b declares both parameters as integers, and : int after the parentheses declares the return type. Passing numeric strings like "6" and "7" still works because PHP coerces them to int by default — passing something that truly isn't numeric, like multiply("six", 7), throws a TypeError instead of silently producing garbage.

Note: a variable declared inside a function only exists inside that function — its own local scope. A function can't see or modify a variable from outside itself just because they share a name, which is generally exactly what you want; it keeps functions self-contained and safe to call without worrying what else in the script happens to be named $total.

Passing arrays to functions

PHP array-arg.php
<?php
function average(array $numbers): float {
    return array_sum($numbers) / count($numbers);
}

$scores = [88, 92, 79, 95];
echo average($scores);
?>
Output
88.5

array_sum() adds up every element, and dividing by count($numbers) gives the mean — a good example of leaning on PHP's built-in array functions instead of writing a manual loop.