Return Values

Yo Yogesh.M Updated 17 Oct 2026
7 min read ·Lesson 49 of 102
In this post

Return Values What Is a Return Value? In simple terms: A return value is the result a function hands back to the code that called it. The call itself then "becomes" that value, so it can be stored, pr

What Is a Return Value?

In simple terms: A return value is the result a function hands back to the code that called it. The call itself then "becomes" that value, so it can be stored, printed, compared, or passed to another function.

Technically: The return statement ends the function's execution immediately and passes the value of its expression back to the caller. A function without a return statement (or with a bare return;) returns null.

$total = calculateTotal($cart);   // the call is replaced by the returned value

Why Returning Values Matters

A function that returns its result is far more useful than one that prints it:

  • The caller decides what to do with the result: display it, save it, send it as JSON, or compare it.
  • The function can be reused in different contexts (web page, API, command-line script, tests).
  • Results can be combined: formatPrice(calculateTotal($cart)).

Basic Usage

Syntax

function functionName(): ReturnType
{
    return expression;
}

Example

<?php
function square(int $number): int
{
    return $number * $number;
}

$result = square(7);

echo $result . "\n";
echo square(3) + square(4) . "\n";
echo "Area of a 12 m square room: " . square(12) . " m²\n";

Output

49
25
Area of a 12 m square room: 144 m²
  • The returned value can be stored ($result), used in arithmetic (square(3) + square(4)), or inserted into a string.
  • : int declares the return type, and PHP checks that the function really returns an integer.

return Ends the Function Immediately

Code after an executed return does not run. This allows early returns for special cases:

<?php
function shippingFee(float $cartTotal, bool $isPremiumMember): int
{
    if ($isPremiumMember) {
        return 0;
    }

    if ($cartTotal >= 999) {
        return 0;
    }

    return 79;
}

echo shippingFee(500, true) . "\n";
echo shippingFee(1200, false) . "\n";
echo shippingFee(500, false) . "\n";

Output

0
0
79

Each special case returns as soon as it is identified. The final return 79 handles everything else. This pattern keeps functions flat and readable.


Functions Without a Return Value: void

A function that performs an action but produces no result declares the return type void:

<?php
function printDivider(int $width = 20): void
{
    echo str_repeat('-', $width) . "\n";
}

printDivider();
printDivider(10);

$result = printDivider(5);
var_dump($result);

Output

--------------------
----------
-----
NULL
  • A void function may use a bare return; to exit early, but it must not return a value. return null; or return 5; in a void function is a compile-time error: "A void function must not return a value".
  • Calling a void function still produces null if you use the call as a value, as var_dump($result) shows.

Returning "Nothing Found": Nullable Return Types

When a function sometimes has no meaningful result, a nullable return type (?Type) states that null is a possible result:

<?php
function findProductPrice(array $catalog, string $sku): ?float
{
    return $catalog[$sku] ?? null;
}

$catalog = ['PEN-01' => 15.0, 'NB-A5' => 60.0];

foreach (['NB-A5', 'BAG-99'] as $sku) {
    $price = findProductPrice($catalog, $sku);

    echo $price === null ? "$sku: not found\n" : "$sku: ₹$price\n";
}

Output

NB-A5: ₹60
BAG-99: not found

The ?float return type warns every caller that the result may be null, so they handle that case. Static analysis tools report code that forgets to check.

Returning false on Failure

Many built-in functions return false when they fail (strpos(), file_get_contents(), array_search()). You can declare this with a union type such as int|false:

<?php
function positionOf(array $items, string $value): int|false
{
    $index = array_search($value, $items, true);

    return is_int($index) ? $index : false;
}

$steps = ['cart', 'address', 'payment'];

var_dump(positionOf($steps, 'cart'));
var_dump(positionOf($steps, 'review'));

Output

int(0)
bool(false)

Because 0 is a valid result, callers must check with === false. In new code, returning null (with ?int) or throwing an exception is often clearer than returning false.


Returning Several Values

A function returns only one value, but that value can be an array. Combined with destructuring, this works like returning several values:

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

[$lowest, $highest] = minMax([4, 9, 1, 7]);

echo "Lowest: $lowest, highest: $highest\n";

Output

Lowest: 1, highest: 9

For more than two or three values, return an associative array so each value has a name:

<?php
function checkoutTotals(array $items, float $gstPercent = 18): array
{
    $subtotal = 0;

    foreach ($items as $item) {
        $subtotal += $item['price'] * $item['qty'];
    }

    $gst = round($subtotal * $gstPercent / 100, 2);

    return [
        'subtotal' => $subtotal,
        'gst' => $gst,
        'total' => $subtotal + $gst,
    ];
}

$items = [
    ['price' => 499, 'qty' => 2],
    ['price' => 1299, 'qty' => 1],
];

['subtotal' => $subtotal, 'gst' => $gst, 'total' => $total] = checkoutTotals($items);

printf("Subtotal: ₹%.2f\nGST: ₹%.2f\nTotal: ₹%.2f\n", $subtotal, $gst, $total);

Output

Subtotal: ₹2297.00
GST: ₹413.46
Total: ₹2710.46

In larger applications, a small class (for example, CheckoutTotals with readonly properties) is an even clearer return type, because its properties are documented and type-checked (see PHP OOP).


Functions That Never Return: never (PHP 8.1+)

The never return type declares that a function never returns normally — it always throws an exception or ends the script:

<?php
function fail(string $message): never
{
    throw new RuntimeException($message);
}

function requirePositive(int $value): int
{
    if ($value <= 0) {
        fail("Expected a positive number, got $value");
    }

    return $value;
}

echo requirePositive(5) . "\n";

try {
    requirePositive(-3);
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Output

5
Error: Expected a positive number, got -3

never tells readers and analysis tools that code after a call to fail() is unreachable. Typical uses are helpers that throw errors, redirect and exit, or stop a command-line script. See Mixed and Never Types.


Returning Functions

A function can return another function (a closure). The returned function remembers the values it was created with:

<?php
function multiplier(int $factor): Closure
{
    return fn(int $number): int => $number * $factor;
}

$double = multiplier(2);
$triple = multiplier(3);

echo $double(5) . "\n";
echo $triple(5) . "\n";

Output

10
15

Each call to multiplier() creates a new function with its own $factor. This technique is covered in Closures and Arrow Functions.


Return Types Are Checked

With a declared return type, PHP verifies the returned value:

<?php
function itemCount(array $cart): int
{
    return "3";   // numeric string
}

var_dump(itemCount([]));

Output

int(3)

In the default (coercive) mode, the numeric string "3" is converted to int(3). With declare(strict_types=1);, the same function throws a TypeError. Returning a value that cannot be converted (for example, "three") is a TypeError in both modes. Forgetting to return a value from a non-void function also throws a TypeError ("Return value must be of type int, none returned").


Common Mistakes

Printing Instead of Returning

Effect: The result cannot be reused, tested, or formatted differently.

Fix: Return the value and let the caller print it.

Forgetting to Use the Returned Value

<?php
$name = "  asha ";
trim($name);      // result discarded
echo "[$name]";   // still "  asha "

Fix: Assign the result: $name = trim($name);.

Inconsistent Return Types

Effect: A function that returns an array in one case, false in another, and a string in a third forces every caller to check many possibilities.

Fix: Declare a return type, and keep results consistent — use null or exceptions for "no result" or errors.

Code After return

Effect: The code never runs.

Fix: Move it before the return.

Returning Values From void Functions

Effect: Compile-time error.

Fix: Remove the value, or change the return type.


Best Practices

  • Return results instead of printing them.
  • Declare return types on every function, including void and never.
  • Use early returns to handle special cases first.
  • Use nullable return types (?Type) for "not found" and exceptions for errors.
  • Return associative arrays (or small objects) when a function produces several related values.

Official reference: https://www.php.net/manual/en/functions.returning-values.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting
Ask about this post
AI Ask about this post

Ask questions about Return Values and get answers drawn from it.

Signed-in readers only.