W3docs

PHP Functions: Understanding and Using Them in Your Code

Function is an important concept in programming and in PHP, functions play a crucial role in making code modular, reusable, and organized. They allow developers

A function is a named block of code that performs a specific task. Functions are one of the most important building blocks in PHP: they let you write a piece of logic once and reuse it everywhere, instead of copying the same code into many places. This page covers how to define and call functions, how to pass arguments (including default, type-hinted, by-reference, and variable-length arguments), how return values work, and the scope rules that determine which variables a function can see.

What is a PHP Function?

A PHP function is a reusable block of code that runs only when you call it. You declare a function with the function keyword, followed by a name, a pair of parentheses listing any parameters (the inputs the function accepts), and a body wrapped in { }. A function can optionally hand back a value with the return keyword.

The general shape of a function looks like this:

function functionName($parameter1, $parameter2) {
    // code to run when the function is called
    return $result; // optional
}

A few naming rules: a function name must start with a letter or underscore, may contain letters, numbers, and underscores, and is case-insensitive (sayHello() and SayHello() call the same function). By convention, most modern PHP code uses camelCase or snake_case for user-defined functions.

Why Use PHP Functions?

Using functions has several concrete benefits:

  • Reusability. Write the logic once, call it as many times as you need. Changing the behavior means editing one place instead of hunting down every copy.
  • Readability. A well-named function (calculateTax()) tells a reader what happens without making them read how.
  • Modularity. Breaking a complex task into smaller functions makes each piece easier to understand, test, and debug.
  • Fewer bugs. Less duplicated code means fewer places for the same mistake to hide.

How to Define and Call a Function

Defining a function does nothing on its own — the body only runs when you call it by writing its name followed by parentheses. The example below defines a function with no parameters and then calls it twice.

<?php

function greet() {
    echo "Hello from a function!\n";
}

greet(); // call it
greet(); // call it again

?>

Output:

Hello from a function!
Hello from a function!

Simple Function That Returns a Value

A function that takes no parameters and returns a string:

php— editable, runs on the server

Output: Hello, World!

Function Parameters and Arguments

A parameter is the variable named in the function definition; an argument is the actual value you pass when calling it. PHP gives you several ways to work with them.

Passing Arguments

The following function takes two parameters and returns their sum. We pass 5 and 10 as arguments.

php— editable, runs on the server

Output: 15

Default Parameter Values

A parameter can have a default value, used when the caller omits that argument. Parameters with defaults must come after required ones.

<?php

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

echo greet("Anna") . "\n";          // uses the default greeting
echo greet("Anna", "Welcome");      // overrides the default

?>

Output:

Hello, Anna!
Welcome, Anna!

Type Declarations

You can declare the expected type of each parameter and the return value. This makes a function self-documenting and lets PHP throw an error when it receives the wrong type.

<?php

function multiply(int $a, int $b): int {
    return $a * $b;
}

echo multiply(4, 3);

?>

Output: 12

Passing Arguments by Reference

By default, PHP passes arguments by value — the function works on a copy, and the original variable is unchanged. Prefix a parameter with & to pass it by reference, letting the function modify the caller's variable directly.

<?php

function addOne(&$number) {
    $number++;
}

$count = 10;
addOne($count);
echo $count;

?>

Output: 11

Variable-Length Argument Lists

When you do not know how many arguments will be passed, the ... (splat) operator collects them all into an array.

<?php

function sumAll(...$numbers) {
    return array_sum($numbers);
}

echo sumAll(1, 2, 3, 4, 5);

?>

Output: 15

Returning Values

A function returns a value with the return keyword. return also stops the function immediately — any code after it is skipped. A function with no return (or return; with no value) returns null. To return several values at once, return an array (or a list() can unpack it on the receiving side).

<?php

function minMax($a, $b) {
    if ($a < $b) {
        return [$a, $b]; // returns and exits here
    }
    return [$b, $a];
}

[$min, $max] = minMax(8, 3);
echo "Min: $min, Max: $max";

?>

Output: Min: 3, Max: 8

For a deeper look, see the PHP return statement chapter.

Variable Scope

Variables created inside a function are local to that function — they do not exist outside it, and the function cannot see variables defined in the surrounding (global) scope unless you import them with the global keyword or pass them as arguments.

<?php

$message = "outside";

function showScope() {
    // $message from the global scope is NOT visible here
    $message = "inside";
    echo $message;
}

showScope();        // prints the local value
echo "\n";
echo $message;      // prints the global value, untouched

?>

Output:

inside
outside

Scope is a common source of confusion for beginners — the PHP variable scope chapter explains global, static, and local variables in detail. See also the PHP Variables chapter for the basics.

Common Mistakes to Avoid

  • Calling a function before it returns what you expect — remember return only gives back a value; you still need to echo or store it. add(5, 10); on its own produces nothing visible.
  • Putting a default parameter before a required one — PHP requires defaults to come last.
  • Expecting changes to leak out — without &, modifying a parameter inside a function does not change the caller's variable.
  • Re-declaring a function name — you cannot define two functions with the same name; PHP throws a fatal error.

Conclusion

PHP functions are the foundation of organized, reusable code. Once you are comfortable defining functions, passing arguments (with defaults, types, references, and variadics), returning values, and reasoning about scope, you can break any large problem into clean, testable pieces. Next, explore working with PHP Arrays and PHP Strings, which functions frequently operate on.

Practice

Practice
What are the key characteristics of functions in PHP?
What are the key characteristics of functions in PHP?
Was this page helpful?