A function packages up a piece of logic so it can be reused by name instead of retyped — the same idea from Intro to Programming, with PHP's syntax.
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Priya"); // "Hello, Priya!"
?><?php
function greet($name = "Guest") {
return "Hello, $name!";
}
echo greet(); // "Hello, Guest!"
echo greet("Amit"); // "Hello, Amit!"
?>PHP lets you optionally declare parameter and return types — not required, but a good habit for catching mistakes early:
<?php
function add(int $a, int $b): int {
return $a + $b;
}
echo add(2, 3); // 5
// add("two", 3); // TypeError — "two" cannot be coerced to an int
?>PHP functions only return one value directly, but that value can be an array — a common way to send back several related pieces of data at once:
<?php
function minMax(array $numbers): array {
return ["min" => min($numbers), "max" => max($numbers)];
}
$result = minMax([4, 9, 1, 7]);
echo $result["min"] . " / " . $result["max"]; // "1 / 9"
?>A compact syntax for short, single-expression functions — you already saw these with array_map() and array_filter() in the Array Functions lesson:
<?php
$double = fn($n) => $n * 2;
echo $double(5); // 10
?>fn vs. an anonymous function
An arrow function (fn) automatically has access to variables from the surrounding scope, without needing to explicitly import them — a regular anonymous function needs a use (...) clause to do the same thing. This is the main practical difference between the two.