PHP Functions

Write reusable functions with parameters, default values, return values and type declarations.

Lesson 8 of 86Beginner17 min read

A function packages a piece of code under a name so you can run it whenever you need it. PHP comes with thousands of built-in functions, such as strlen(), count() and date(), and you can write your own for tasks that are specific to your site.

Functions keep pages tidy. Instead of repeating the code that formats a price in ten places, you write formatPrice() once and call it everywhere. If the format changes, you update a single function.

In this lesson you'll define functions, pass in values, return results, set default values, add type declarations that catch mistakes, and learn how variables inside and outside functions are kept separate.

Defining and calling

PHP
function greet($name) {
    return "Hello, $name!";
}

echo greet("Noor");   // Hello, Noor!
  • function starts the definition, followed by the name and parameters in brackets.
  • return sends a value back to where the function was called and ends the function.
  • Call it by name with arguments in brackets.

Function names are not case-sensitive in PHP, but always call a function exactly as you defined it to keep code readable.

Default values and named arguments

Give a parameter a default value with = to make it optional:

PHP
function formatPrice($amount, $currency = "£") {
    return $currency . number_format($amount, 2);
}

echo formatPrice(5);          // £5.00
echo formatPrice(5, "€");     // €5.00

PHP 8 also supports named arguments, where you pass values by parameter name in any order: formatPrice(currency: "$", amount: 9.5). They make calls with several options much easier to read.

Type declarations

You can state the type each parameter must have, and the type the function returns:

PHP
function addTax(float $price, float $rate = 0.2): float {
    return $price * (1 + $rate);
}

If someone calls addTax("abc"), PHP throws a clear error instead of quietly producing nonsense. Common types are int, float, string, bool and array. Use : void for functions that don't return anything, and a ? before a type, such as ?string, to also allow null.

Variable scope

Variables created inside a function are local: they exist only while the function runs. Variables from outside the function aren't visible inside it either:

PHP
$siteName = "Codevra";

function footer() {
    return "© " . $siteName;   // Warning: Undefined variable
}

The fix is to pass what the function needs as a parameter: function footer($siteName). Keeping functions self-contained like this makes them predictable and easy to reuse.

Nullable and union types

Sometimes a parameter can be one of several types, or may be missing. PHP's type declarations can say so:

PHP
function describe(int|float $amount, ?string $label = null): string {
    return ($label ?? "Total") . ": " . $amount;
}

echo describe(2.5);              // Total: 2.5
echo describe(10, "Subtotal");   // Subtotal: 10
  • int|float is a union type: either type is accepted (PHP 8.0 and later).
  • ?string means "a string or null", which is common for optional values.
  • A return type of ?array means the function may return null, for example when nothing was found.

Add declare(strict_types=1); as the first statement of a file to stop PHP converting values between scalar types automatically, so passing "5" to an int parameter becomes an error instead of being quietly converted. The type declarations lesson covers all the options.

Returning more than one value

A function returns a single value, but that value can be an array. Combined with array destructuring, this gives a neat way to return several results:

PHP
function minMax(array $numbers): array {
    return [min($numbers), max($numbers)];
}

[$lowest, $highest] = minMax([4, 9, 2]);
echo "$lowest to $highest";   // 2 to 9

For results with named parts, return an associative array and destructure by key, ['total' => $total] = summary($order);, or return a small object. Both keep the call site readable.

PHP Functions Syntax

Function syntax

function name(type $param, type $optional = default): returnType {
    // body
    return $value;
}

name($arg);
name(optional: $value, param: $arg);   // named arguments

PHP Functions Summary

  • function name($param) { return $value; } defines a function.
  • Default values make parameters optional; named arguments set them by name.
  • Type declarations like float $price and : float catch wrong values early.
  • Variables inside a function are local; pass outside values in as parameters.
  • require_once shares functions between pages.

PHP Functions Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Small helper functions

PHP
<?php
function formatPrice(float $amount, string $currency = "£"): string {
    return $currency . number_format($amount, 2);
}

function isOnSale(float $price, float $was): bool {
    return $price < $was;
}

$price = 8.5;
$was = 12;

echo formatPrice($price) . "\n";
echo formatPrice($price, "$") . "\n";
echo isOnSale($price, $was) ? "On sale!" : "Full price";
Output
£8.50
$8.50
On sale!
Line-by-line explanation
  1. Lines 2 to 4Typed parameters, a default currency and a string return type.
  2. Lines 6 to 8A yes/no function returns a bool.
  3. Lines 13 to 14The default "£" is used unless another currency is passed.
Example 2

Working with arrays

PHP
<?php
function average(array $numbers): float {
    if (count($numbers) === 0) {
        return 0;
    }
    return array_sum($numbers) / count($numbers);
}

function grade(float $score): string {
    return match (true) {
        $score >= 80 => "Merit",
        $score >= 50 => "Pass",
        default => "Retake",
    };
}

$scores = [72, 88, 91];
$avg = average($scores);
echo round($avg, 1) . " = " . grade($avg);
Output
83.7 = Merit
Line-by-line explanation
  1. Lines 3 to 5Return early to avoid dividing by zero on an empty array.
  2. Lines 10 to 14match (true) picks the first arm whose condition is true.
  3. Line 19The result of one function is passed straight into another.
Example 3

Scope in action

PHP
<?php
$counter = 10;

function addOne(int $n): int {
    $n = $n + 1;
    return $n;
}

$result = addOne($counter);
echo "result: $result, counter: $counter";
Output
result: 11, counter: 10
Line-by-line explanation
  1. Line 4$n is a local copy of the value passed in.
  2. Line 5Changing $n doesn't affect $counter outside the function.
  3. Line 10Only the returned value carries the change back.

Common PHP Functions Mistakes

Echoing instead of returning

Don't
function total($a, $b) {
    echo $a + $b;
}
$sum = total(2, 3) * 2;   // prints 5, and $sum is 0
Do
function total($a, $b) {
    return $a + $b;
}
$sum = total(2, 3) * 2;   // 10

A function that only echoes returns null, which counts as 0 in maths.

Using an outside variable inside a function

Don't
$rate = 0.2;
function tax($price) {
    return $price * $rate;   // $rate is undefined here
}
Do
function tax($price, $rate = 0.2) {
    return $price * $rate;
}

Required parameter after an optional one

Don't
function book($date = "today", $name) { }
Do
function book($name, $date = "today") { }

Optional parameters belong at the end, or callers can't leave them out.

PHP Functions in Real Projects

Functions on PHP sites

WordPress themes are full of functions such as the_title() and get_permalink(), and frameworks like Laravel give you helpers like route() and asset(). On your own projects, functions such as formatPrice(), sendWelcomeEmail($user) and renderProductCard($product) keep each page short and consistent.

PHP Functions FAQ

Can a PHP function change a variable passed to it?

Only if the parameter is declared by reference with &: function addOne(&$n) { $n++; }. Normal parameters receive a copy, so changes stay inside the function. Returning a new value is usually clearer than changing the caller's variable.

Should I use the global keyword?

Avoid it. global $db; lets a function read and change an outside variable, but it hides the function's real inputs and makes it hard to test or reuse. Pass the values the function needs as parameters, or put related functions and their shared data in a class.

How do I write a function that accepts any number of arguments?

Add a variadic parameter with ...: function total(float ...$prices): float { return array_sum($prices); }. Inside the function, $prices is an array, so total(1.5, 2, 3) returns 6.5. See the variadic and named arguments lesson.

What is the difference between a function and a closure?

A named function is declared with a name and can be called from anywhere after it is defined. A closure, or anonymous function, is a value: you store it in a variable or pass it to functions such as array_map. Closures can capture outside variables with use, and arrow functions capture them automatically.

Can a function call itself in PHP?

Yes, that's recursion. It's useful for nested data such as category trees or folders within folders. Every recursive function needs a stopping condition, otherwise PHP eventually stops with a memory or stack error.

PHP Functions Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the function so it returns the square of $n.

 square($n) {
     $n * $n;
}
Predict the outputeasy

What does this print?

function hello($name = "friend") {
    return "Hi $name";
}
echo hello() . ", " . hello("Ana");
Predict the outputmedium

What does this print?

$x = 5;
function double($x) {
    $x = $x * 2;
    return $x;
}
double($x);
echo $x;
Multiple choicemedium

What does : float after a function's brackets mean?

Multiple choicehard

Why can't a function read a variable defined outside it?

PHP Functions Quiz

5 questions to check what you learned.

  1. Which keyword defines a function in PHP?

    • def
    • func
    • fn only
    • function
  2. Can a function read a variable defined outside it, without passing it in?

    • No, function variables are local
    • Yes, always
    • Only if it's a string
    • Only inside loops
  3. What does a function return if it has no return statement?

    • 0
    • null
    • false
    • An empty string
  4. What are named arguments?

    • Passing values by parameter name, e.g. f(price: 5)
    • Arguments that are strings
    • Arguments with default values
    • Global variables
  5. What does : string after a function's brackets mean?

    • The function takes a string
    • The function is called string
    • The function returns a string
    • It's a comment