agyanadda@gmail.com

PHP Functions

Functions 1 min read Updated Dec 1, 2026 Topic 15 of 36

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 : void when nothing is returned)
  • return sends 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

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which return type means a function returns nothing?

Exercise 2 True / False

Named arguments let you pass values in any order.

Exercise 3 Fill in the Blank

An arrow function starts with the keyword ___.

Frequently Asked Questions

No, but always call them exactly as declared. Variable names, however, are case-sensitive.