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
function add($a, $b) {
return $a + $b;
}
echo add(3, 4);
?>
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 function greet($name, $greeting = "Hello") { return "$greeting, $name!"; } echo greet("Sam") . "\n"; echo greet("Priya", "Welcome"); ?>
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
function multiply(int $a, int $b): int {
return $a * $b;
}
echo multiply(6, 7) . "\n";
echo multiply("6", "7");
?>
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.
$total.Passing arrays to functions
<?php
function average(array $numbers): float {
return array_sum($numbers) / count($numbers);
}
$scores = [88, 92, 79, 95];
echo average($scores);
?>
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.