Return Values

Ma Mahalakshmi V Updated 14 Nov 2026
7 min read ·Lesson 69 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

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

Signed-in readers only.