Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 147 Β· Functions

Functions

Learn how to write PHP functions - defining and calling them, parameters, return values, naming rules, calling before the definition, conditional functions and function_exists.

As your scripts grow, you'll notice the same few lines appearing again and again: formatting a price, validating an email address, building a greeting. A function gives a block of code a name, so you can write it once and run it wherever you need it, with different input each time. Change the function, and every place that uses it gets the fix.

You've already called plenty of PHP's built-in functions, such as strlen(), count() and number_format(). This lesson shows you how to write your own: defining and calling them, passing values in, returning results, naming them well, and how PHP finds functions (including why you can call a function before its definition, and when you can't). It opens the Functions chapter; the next lessons go deeper into Parameters and Arguments, Type Declarations and Variable Scope.

Defining and calling a function

A function definition starts with the keyword function, then the function's name, a pair of parentheses and a body in braces:

PHP
function sayHello()
{
    echo 'Hello!', PHP_EOL;
}

Defining a function doesn't run it. The body runs only when you call the function by writing its name followed by parentheses:

PHP A first function

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each printDivider(); jumps into the function, runs its body, and comes back to the statement after the call. If you later want the divider to be 40 dashes instead, you change one line instead of three.

In the PSR-12 / PER coding style used in this tutorial, the opening brace of a function goes on its own line, unlike the braces of if and loops. It's a convention, not a rule PHP enforces, but you'll see it in almost all modern PHP code.

Parameters: passing values in

A function becomes far more useful when it can work with different data on each call. List parameters inside the parentheses. Each one is a variable that receives a value, called an argument, when the function is called:

PHP Functions with parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Arguments are matched to parameters by position: in printBox('PHP', 11), 'PHP' goes into $text and 11 into $width. If you pass too few arguments, PHP throws an ArgumentCountError ("Too few arguments to function printBox(), 1 passed … and exactly 2 expected"). Extra arguments are silently ignored, which can hide mistakes.

Parameters can do much more: have default values, be passed by name (printBox(width: 20, text: 'Hi')), accept any number of values, or modify the caller's variables. All of that is in Parameters and Arguments.

Return values

Printing from inside a function is limiting: the caller can't reuse, store or combine what was printed. Most functions should instead return a value with the return statement. The function call then becomes that value, just like strlen('abc') becomes 3:

PHP Returning a result

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Because circleArea() returns a number instead of printing it, the caller can round it, divide two results, or feed it into another function. As a rule of thumb, functions that compute something should return it, and printing should happen in a few places close to the output. That separation also makes functions easy to test (see Testing PHP Code).

return ends the function

return doesn't only provide a value: it stops the function immediately. Any code after it doesn't run. That lets you exit as soon as you know the answer, with several return statements in one function:

PHP Several returns, and no return

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Exiting early for the special cases, and keeping the general case at the bottom, is the guard-clause style from break, continue and Loop Control.

A function that ends without return, or with a bare return;, returns null. So $result in the example is NULL. For a function that's never meant to return a value, you can say so with the void return type, as shown below.

Returning several values

A function returns exactly one value, but that value can be an array. Combined with destructuring, that's a neat way to hand back several results at once:

PHP Returning an array of results

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Returning an associative array with named keys is clearer than a list when there are more than two values, since the caller doesn't have to remember the order. When the same group of values travels through your whole program, a small class is better still; you'll learn to write those in Object-Oriented Programming in PHP. Destructuring is explained in Destructuring and Spread.

A preview of type declarations

The functions so far accept anything. Call circleArea('large') and PHP will try to square a string and throw a TypeError deep inside the function. Modern PHP lets you declare what each parameter expects and what the function returns:

PHP Declaring parameter and return types

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

float $price means the argument must be a float (an int such as 80 is also accepted and becomes 80.0). : float after the parentheses declares the return type, and : void says the function returns nothing. With declare(strict_types=1); at the top of the file, passing the string '80' is rejected with a clear TypeError instead of being converted silently. The try/catch block catches that error so the script can print it; Exceptions explains how that works.

Types are documentation that PHP checks for you, and every modern PHP project uses them. Type Declarations covers them in full; from here on, examples with functions use them.

Naming functions

A function's name should say what it does, so that a call reads like a sentence. Some guidelines:

  • Start with a verb for functions that do something: sendInvoice(), calculateTotal(), formatDate(). Functions that answer a yes/no question often start with is, has or can: isValidEmail(), hasDiscount().
  • Use camelCase for your own functions, as the PSR coding standards recommend: calculateTotal, not calculate_total. PHP's built-in functions mostly use snake_case (array_key_exists, str_contains) for historical reasons, so you'll see both styles side by side.
  • Allowed characters: a name starts with a letter or underscore, followed by letters, digits or underscores. Don't start your own names with two underscores: PHP reserves those for "magic" names like __construct.
  • Be specific. process() or handle() says nothing; resizeImage() and importCustomers() say everything.

Function names are case-insensitive in PHP: once formatPrice() exists, FORMATPRICE() and formatprice() call the same function. Don't rely on this; always call a function exactly as it's written. Variable names, by contrast, are case-sensitive (see Variables).

Each function name can exist only once. Defining a function a second time, even with different capitalization, is a fatal error, and so is reusing the name of a built-in function:

TEXT
Fatal error: Cannot redeclare function formatPrice() (previously declared in main.php:3) in main.php on line 8
Fatal error: Cannot redeclare function strlen() in main.php on line 2

In larger projects, Namespaces let two libraries each have their own format() function without colliding.

Where functions can be defined

Calling before the definition

PHP reads (compiles) the whole file before it runs anything. Functions defined at the top level of a file are registered during that step, so you can call them before the line where they're defined:

PHP Calling a function defined later

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This lets you put the main flow of a script first and the helper functions underneath. In real projects, functions usually live in separate files that are loaded with require or autoloading, covered in Autoloading and Composer.

Conditional functions

The early registration applies only to top-level definitions. A function defined inside an if block (or inside another function) exists only after PHP has executed that definition. Calling it earlier fails. This example fails on purpose on its last call:

PHP A conditional function (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The call to banner() works because the if block already ran. tooEarly() is called before its if block has run, so PHP throws Error: Call to undefined function tooEarly(). Conditional functions are rare in modern code. The main legitimate use is a polyfill: defining a function only if PHP doesn't already provide it.

function_exists()

function_exists('name') returns true if a function with that name is defined, whether it's built in or yours. Polyfills use it to add a newer PHP function on older versions without clashing with the real one on newer versions:

PHP A polyfill guarded by function_exists

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

On our PHP 8.5 server the built-in array_find() exists, so the if block is skipped and the real function runs. On PHP 8.3 the fallback would be defined instead, and the rest of the code works either way. The fn(int $n): bool => $n > 5 part is an arrow function, a small function without a name, covered in Anonymous Functions and Closures.

You can also check for a function before calling an optional extension: function_exists('sodium_crypto_secretbox') tells you whether the sodium extension is installed.

What makes a good function

  • It does one thing. If you need "and" to describe it (validateAndSaveAndEmail), split it up.
  • It's short. Most good functions fit on a screen. Long ones usually hide several smaller ones.
  • It gets its input from parameters and gives its output with return. Functions that read and change outside variables are hard to understand; Variable Scope explains why PHP keeps function variables separate by default.
  • It has a name and types that explain it. A reader should rarely need to open the body to know what a call does.

Functions like this are easy to reuse, to test, and to combine, which is what the rest of this chapter builds on, all the way to Recursion, where a function calls itself.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does this print? function double($n) { return $n * 2; echo "done"; } echo double(4);

    return ends the function immediately, so the echo after it never runs. The call becomes 8, which is printed.
  2. 2. What does var_dump(show()); print, given function show() { echo "hi "; }?

    The function prints "hi " while it runs and then returns nothing, which means it returns null.
  3. 3. Which call works?

    Top-level functions are registered when the file is compiled, so they can be called before their definition. The other options cause fatal errors.
  4. 4. Given function area($w, $h) { return $w * $h; }, what happens with area(3);?

    Missing required arguments throw an ArgumentCountError ("Too few arguments ..."). Default values, covered in the next lesson, make a parameter optional.
  5. 5. What does function_exists('array_find') return on PHP 8.5?

    function_exists() checks built-in and user-defined functions alike, which is what makes it useful for polyfills.

Summary

  • Define a function with function name(params) { ... } and run it by calling name(args); defining alone runs nothing.
  • Parameters receive the arguments by position; too few arguments throw an ArgumentCountError.
  • return sends a value back and ends the function at once; without return, a function returns null. Return arrays (and destructure them) to hand back several values.
  • Prefer functions that return values over functions that print; declare types like float $price and : float (or : void) with declare(strict_types=1);.
  • Name functions with verbs in camelCase; names are case-insensitive and must be unique, including built-in names.
  • Top-level functions can be called before their definition; conditional ones exist only after their definition runs. function_exists() guards polyfills.

Next: Parameters and Arguments