HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to PHPVariablesData TypesOperatorsStringsArraysAssociative ArraysConditions (if / else)Loops (for / foreach / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🔁 Condition & Loop
🧩 Function
🔄 Type & Conversion
PHP›Functions

Functions

Defining functions with function, parameters, return, and default values.

Simple enough for a 5-year-old to understand

function and return

Example code
1
<?php
Start.
DefinitionStart.
2
function square($x) {
A function that takes the input $x.
FunctionA function that takes the input $x.
3
return $x * $x;
Return the result.
FunctionReturn the result.
4
}
End.
FunctionEnd.
5
echo square(5);
Call → 25
Output / InputCall → 25
DefinitionFunctionOutput / Input
💡 Hint: If there is no return, the function returns NULL.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Write a function named addUp that adds two numbers and RETURNS them; print addUp(8, 9).

🎯 Expected output: 17

Loading editor…

About this topic

A function is giving a name to a piece of code that performs a task. In PHP, functions can be defined freely outside of classes — unlike Java. There are thousands of built-in functions in the standard library, and the right reflex for most tasks is to look for an existing one before writing your own.

Functions in PHP DO NOT SEE the outer scope. Everything a function needs must be passed as a parameter. This strictness can be annoying at first, but it keeps functions independent and testable.

In modern PHP, declaring parameter and return types is possible and strongly recommended. When used together with strict typing mode, type errors are caught at the time of the call and what the code expects is documented.

What you will learn

  • Defining and calling a function
  • Passing parameters and default values
  • returning values with return
  • Using type declarations
  • The scope rule and why parameters are needed
  • Anonymous functions and arrow functions

When to use?

If you are about to write the same code for the second time, it is time to extract it into a function. Repeating tasks such as validation, formatting, and database access are separated into functions.

Anonymous functions are used to provide criteria to functions like array_map, array_filter, and usort. For single-line tasks, the arrow function format is shorter and automatically captures outer variables.

Common mistakes

Wrong

$taxRate = 0.2;
function addTax(float $amount): float {
    return $amount * (1 + $taxRate);
}
echo addTax(100);

The $taxRate is undefined inside the function — functions in PHP do not see the outer scope. It throws a warning and produces an incorrect result by treating the rate as zero. The value must be passed as a parameter.

Correct

$taxRate = 0.2;
function addTax(float $amount, float $rate): float {
    return $amount * (1 + $rate);
}
echo addTax(100, $taxRate);

Wrong

function greet(string $greeting = "Hello", string $name): string {
    return "$greeting $name";
}

A parameter with a default value cannot come BEFORE a parameter without a default value; PHP throws a "Required parameter follows optional parameter" warning. Defaults are always written at the end.

Correct

function greet(string $name, string $greeting = "Hello"): string {
    return "$greeting $name";
}

Wrong

function getTotal(array $items) {
    $sum = 0;
    foreach ($items as $i) {
        $sum += $i;
    }
    echo $sum;
}
$total = getTotal([1, 2, 3]);

The function prints with echo instead of returning with return; $total remains null. A function that calculates a value should return it — printing is the job of the caller. This separation makes the function reusable.

Correct

function getTotal(array $items): int {
    $sum = 0;
    foreach ($items as $i) {
        $sum += $i;
    }
    return $sum;
}
$total = getTotal([1, 2, 3]);

Frequently asked questions

How do I access an outer variable from inside a function?

By passing it as a parameter. The global keyword technically exists but should not be used: it makes the function dependent on external state, untestable, and makes it harder to find the source of errors.

Is type declaration mandatory?

It is not mandatory but strongly recommended. Type declaration is both documentation and protection: when the wrong type is passed, the error appears at the call site, not deep inside the code. Its impact is highest when used with strict typing mode.

What is the difference between an arrow function and an anonymous function?

An arrow function consists of a single expression and automatically captures outer variables. An anonymous function can be multi-line, but you must explicitly capture outer variables using use. For short transformations, arrow functions are much more readable.

Summary

PHP functions do not see the outer scope; everything they need must be passed as parameters. A function that calculates a value should return it, default parameters should be placed at the end, and type declarations should be used.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code