PHP Functions

A function is a named, reusable block of PHP code that runs only when you call it, letting you organize logic, avoid repetition, and pass data in and out through parameters and return values.

What Is a PHP Function?

A function groups a set of statements under a single name so you can run them whenever you need them, instead of writing the same code over and over. PHP ships with hundreds of built-in functions, but you can also define your own. A user-defined function is created with the function keyword, followed by a name, a pair of parentheses that may hold parameters, and a body wrapped in curly braces. The code inside the body does not run when the file is loaded; it runs only when the function is called by name.

Defining and calling a simple function

<?php
function greet() {
    echo "Hello, welcome to the site!";
}

// The function runs only when we call it
greet();
?>

Function names in PHP follow the same rules as identifiers: they must start with a letter or underscore, followed by any number of letters, numbers, or underscores. Unlike variables, function names are case-insensitive, so greet() and GREET() refer to the same function. Even so, it is good practice to call a function using the exact name you defined it with, and to choose clear, descriptive names that say what the function does.

Parameters and Arguments

Parameters are the named placeholders listed inside the parentheses of a function definition. When you call the function, the actual values you pass in are called arguments, and they are assigned to the parameters in order. Parameters let a single function work with different data each time it runs. You can declare as many parameters as you need, separating them with commas.

Passing arguments to parameters

<?php
function greetUser($name, $city) {
    echo "Hi $name from $city!";
}

greetUser("Ravi", "Chennai");
// Output: Hi Ravi from Chennai!
?>
Note: The order of arguments matters. The first argument you pass is assigned to the first parameter, the second to the second, and so on. PHP 8.0 and later also lets you pass arguments by name, such as greetUser(city: "Chennai", name: "Ravi"), which frees you from remembering the exact order.

Default Parameter Values

You can give a parameter a default value by assigning it in the function definition. If the caller omits that argument, PHP uses the default instead. This makes some arguments optional and keeps common calls short. Parameters with defaults should be listed after any required parameters, otherwise the optional one cannot actually be skipped.

Using default values

<?php
function makeCoffee($type = "espresso") {
    echo "Making a cup of $type.\n";
}

makeCoffee();          // Making a cup of espresso.
makeCoffee("latte");    // Making a cup of latte.
?>

Returning Values

Most useful functions send a result back to the code that called them using the return statement. When PHP reaches return, it immediately stops running the function and hands the value back to the caller, where you can store it in a variable, print it, or feed it into another expression. A function without a return statement returns null by default. A function can only return a single value, but that value may be an array or an object holding several pieces of data.

  • return sends a value back and ends the function right away.
  • Any statements written after a return that runs are never executed.
  • A function with no return, or a bare return;, produces the value null.
  • The returned value can be captured in a variable or used directly in a larger expression.

Type Declarations

Modern PHP lets you declare the expected type of each parameter and of the return value. Type declarations make your intent clear and cause PHP to raise an error when the wrong kind of data is supplied, catching mistakes early. Common scalar types include int, float, string, and bool, and you can mark a return type of void when a function returns nothing. Placing declare(strict_types=1) at the very top of a file makes these checks strict, so PHP will not silently convert a value from one type to another.

Typed parameters and return type

<?php
declare(strict_types=1);

function addNumbers(int $a, int $b): int {
    return $a + $b;
}

$total = addNumbers(4, 6);
echo $total; // 10
?>
Note: Add declare(strict_types=1); as the first line of a file to enforce exact types. In strict mode, calling addNumbers("4", 6) throws a TypeError instead of quietly turning the string into a number, which helps you find bugs sooner.
ConceptSyntax examplePurpose
Definitionfunction name() { ... }Creates a reusable named block of code.
Parameterfunction f($x)Placeholder that receives an input value.
Default valuefunction f($x = 10)Makes an argument optional.
Return valuereturn $result;Sends a value back to the caller.
Parameter typefunction f(int $x)Restricts the input to a given type.
Return typefunction f(): stringDeclares the type of the returned value.

As you write more PHP, you will lean on functions to break large problems into small, testable pieces. Keep each function focused on one clear job, give it a descriptive name, use parameters for anything that changes between calls, and return a value rather than printing directly when the result might be reused. These habits make your code easier to read, debug, and extend.

Exercise: PHP Functions

What happens if a parameter has a default value and the caller omits it?