Functions

A function is a named, reusable block of code. You give it inputs (parameters), it does its work, and it can hand back a result with return. Functions keep scripts organised and remove repetition — and PHP's own library is simply thousands of ready-made functions.

Defining and calling

PHP
<?php

function printBanner(string $title): void
{
    $line = str_repeat("*", strlen($title) + 4);
    echo "$line\n* $title *\n$line\n";
}

printBanner("Weekly report");
printBanner("Totals");
Output
*****************
* Weekly report *
*****************
**********
* Totals *
**********

A function definition has the keyword function, a name (camelCase by convention), a parameter list with optional types, an optional return type after a colon, and a body in braces. void means it returns nothing. Function names are case-insensitive, but always call them exactly as defined.

Returning values

return sends a value back to the caller and ends the function immediately:

PHP
<?php

function circleArea(float $radius): float
{
    return M_PI * $radius ** 2;
}

function describe(int $n): string
{
    if ($n < 0) {
        return "negative";
    }
    if ($n === 0) {
        return "zero";
    }
    return $n % 2 === 0 ? "positive and even" : "positive and odd";
}

printf("%.2f\n", circleArea(2.5));
echo describe(-3), ", ", describe(0), ", ", describe(42), "\n";
Output
19.63
negative, zero, positive and even

A function without a return statement returns null.

Functions can be called before they're defined

PHP reads the whole file before running it, so top-level functions can be called from code above their definition:

PHP
<?php

echo greet("Ana"), "\n";

function greet(string $name): string
{
    return "Hello, $name!";
}
Output
Hello, Ana!

Functions defined inside an if, or in a file you include, only exist once that code has run.

Functions calling functions

Small functions combine into larger ones, each easy to understand and test on its own:

PHP
<?php

function average(array $values): float
{
    return array_sum($values) / count($values);
}

function grade(float $score): string
{
    return match (true) {
        $score >= 90 => "A",
        $score >= 80 => "B",
        $score >= 70 => "C",
        default => "D",
    };
}

function summary(array $marks): string
{
    $avg = average($marks);
    return sprintf("Average %.1f (%s)", $avg, grade($avg));
}

echo summary([72, 88, 95, 61, 79]), "\n";
Output
Average 79.0 (C)

Built-in and user functions

PHP's built-in functions are called the same way as your own. Check whether one exists with function_exists — and note that you can't define a function with the same name as an existing one. That mistake is caught while PHP compiles the file, so nothing runs, not even the var_dump lines above it:

PHP
<?php

var_dump(function_exists('str_contains'));
var_dump(function_exists('myHelper'));

function strlen(string $s): int
{
    return 0;
}
Output
Fatal error: Cannot redeclare function strlen() in main.php on line 6
Stack trace:
#0 {main}

Including files

As programs grow, functions move into separate files. require loads a file and stops with a fatal error if it's missing; include only warns. The _once variants skip files already loaded, so functions aren't declared twice:

PHP helpers.php
<?php

function slugify(string $text): string
{
    return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($text)), '-');
}

function excerpt(string $text, int $words = 5): string
{
    $parts = explode(' ', $text);
    return implode(' ', array_slice($parts, 0, $words)) . (count($parts) > $words ? '…' : '');
}
PHP main.php
<?php

require_once __DIR__ . '/helpers.php';

$title = "Ten Tips for Faster PHP!";
echo slugify($title), "\n";
echo excerpt("PHP functions keep your code organised and easy to reuse"), "\n";
Output
ten-tips-for-faster-php
PHP functions keep your code…

__DIR__ makes the path relative to the current file rather than wherever the script was started from. In larger projects, Composer's autoloader loads classes automatically (lesson 43), and you rarely write require by hand.

What makes a good function

  • It does one thing, and its name says what: calculateShipping, isValidEmail, formatPrice.
  • It takes inputs as parameters and gives results as a return value, rather than reading and writing global variables (lesson 30).
  • It declares types for parameters and return values (lesson 29).
  • It's short enough to read without scrolling.
  • It separates calculating from printing: return a string and let the caller echo it, so the function can be reused in a web page, an email or a test.

Try it yourself

Write isPalindrome, ignoring case and spaces, and test it on a few phrases.

Try it yourself · main.php
Edit the code, copy it into main.php, then run it with php main.php (PHP 8.5). How to install PHP
Output
Racecar: yes
Never odd or even: yes
PHP rocks: no