A function is a named block of code you can reuse.
function greet(string $name, string $time = 'morning'): string
{
return "Good $time, $name!";
}
echo greet('Asha'); // Good morning, Asha!
echo greet('Ravi', 'evening');
Parts
- Parameters with optional types:
string $name - Default values:
$time = 'morning' - Return type:
: string(use: voidwhen nothing is returned) returnsends back a value and ends the function
Named arguments (PHP 8)
greet(time: 'night', name: 'Neha'); — order does not matter, and code is easier to read.
Nullable and union types
?string $city (string or null), int|float $amount.
Anonymous and arrow functions
$square = function ($n) { return $n * $n; };
$double = fn($n) => $n * 2; // PHP 7.4+
These are used with array_map, array_filter and usort.
PHP also has 1,000+ built-in functions — always check before writing your own.
Example
Example — Reusable fee calculator
PHP
<?php
declare(strict_types=1);
function calculateFee(float $fee, float $discount = 0, bool $addGst = true): float
{
$amount = $fee - ($fee * $discount / 100);
if ($addGst) {
$amount += $amount * 0.18;
}
return round($amount, 2);
}
function formatRupees(float $amount): string
{
return '₹' . number_format($amount, 2);
}
echo formatRupees(calculateFee(5000)) . '<br>';
echo formatRupees(calculateFee(5000, 10)) . '<br>';
echo formatRupees(calculateFee(fee: 5000, addGst: false)) . '<br>';
$double = fn($n) => $n * 2;
echo 'Double of 21: ' . $double(21);
Output: ₹5,900.00 / ₹5,310.00 / ₹5,000.00 / Double of 21: 42