Arrays & Functions Lesson 11 of 17
PHP Functions
Write PHP functions with parameters, default values, type declarations and return types, pass by reference, use variable scope correctly, and write arrow functions.
Functions package code into named, reusable pieces. PHP has thousands of built-in functions, and you'll write your own for anything you do more than once, like computing a grade or formatting pesos.
Defining a function
<?php
function peso(float $amount): string {
return "₱" . number_format($amount, 2);
}
function average(array $grades): float {
return array_sum($grades) / count($grades);
}
echo peso(1234.5), "\n";
echo peso(average([88, 91, 85])), "\n";
Output
₱1,234.50 ₱88.00
float $amountis a type declaration: the function expects a number.: stringafter the parentheses is the return type.- Types are optional in PHP, but they catch mistakes early and make code self-explaining.
Default values and named arguments
<?php
function jeepFare(float $km, bool $discounted = false): float {
$fare = 13 + max(0, $km - 4) * 1.80;
return round($discounted ? $fare * 0.8 : $fare, 2);
}
echo jeepFare(9), "\n";
echo jeepFare(9, true), "\n";
echo jeepFare(discounted: true, km: 6), "\n";
Output
22 17.6 13.28
Returning several values
<?php
function stats(array $g): array {
return [min($g), max($g), array_sum($g) / count($g)];
}
[$low, $high, $avg] = stats([88, 72, 95, 81]);
echo "Low $low, high $high, average $avg";
Output
Low 72, high 95, average 84
Variable scope
Variables outside a function are not visible inside it (unlike JavaScript):
<?php
$school = "Rizal NHS";
function showSchool() {
return $school ?? "(not visible here)";
}
echo showSchool();
Output
(not visible here)
Pass what a function needs as parameters. (The global keyword exists, but relying on it makes code hard to follow.)
Pass by reference
<?php
function addBonus(array &$grades, int $bonus): void {
foreach ($grades as &$g) {
$g = min(100, $g + $bonus);
}
}
$scores = [88, 97, 75];
addBonus($scores, 5);
echo implode(", ", $scores);
Output
93, 100, 80
The & makes the parameter refer to the caller's variable, so changes stick. void means the function returns nothing.
Arrow functions and closures
<?php
$vat = 0.12;
$withVat = fn($price) => $price * (1 + $vat); // can read $vat automatically
echo $withVat(250), "\n";
$double = function ($n) { return $n * 2; };
echo $double(21);
Output
280 42
Organizing functions in a separate file
Put your functions in a file like functions.php and load it on every page that needs them:
<?php
require_once "functions.php";
echo peso(99);
The Include lesson explains require and include in detail.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04