Skip to content

PHP Tutorial Functions

Return Values

Lesson 104 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

So far, our functions have printed text. A more useful function returns a value so the caller can decide what to do with it.

index.php
PHP
<?php
function add(int $a, int $b): int
{
    return $a + $b;
}

$result = add(3, 4);

echo $result;
Output
OUTPUT
7

return does two things: it sends the value back, and it ends the function immediately.

return vs echo

echoreturn
PurposeShows textGives a value back
Caller can store the valueNoYes
Ends the functionNoYes

A function that only prints cannot be reused in a calculation. A function that returns can be used anywhere.

index.php
PHP
<?php
function priceWithTax(float $price): float
{
    return $price * 1.18;
}

$total = priceWithTax(100) + priceWithTax(200);

echo $total;
Output
OUTPUT
354

Code after return never runs

index.php
PHP
<?php
function test(): string
{
    return "first";
    echo "never printed";
}

echo test();
Output
OUTPUT
first

Early return

Use return early to handle special cases and keep the rest of the code simple.

index.php
PHP
<?php
function divide(float $a, float $b): float|string
{
    if ($b === 0.0) {
        return "Cannot divide by zero";
    }

    return $a / $b;
}

echo divide(10, 4) . "\n";
echo divide(5, 0);
Output
OUTPUT
2.5
Cannot divide by zero

Return several values

A function returns only one value, but that value can be an array.

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

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

echo "Lowest $lowest, highest $highest";
Output
OUTPUT
Lowest 2, highest 9

An associative array is clearer when there are many values.

index.php
PHP
<?php
function stats(array $numbers): array
{
    return [
        "sum" => array_sum($numbers),
        "average" => array_sum($numbers) / count($numbers),
    ];
}

$result = stats([2, 4, 6]);

echo "Sum: {$result['sum']}, average: {$result['average']}";
Output
OUTPUT
Sum: 12, average: 4

No return means null

A function with no return gives back null.

index.php
PHP
<?php
function noReturn(): void
{
    $x = 5;
}

var_dump(noReturn());
Output
OUTPUT
NULL

Exercise: a square function

Write square(int $n): int that returns $n * $n, and use it to print the square of 9.

Show a possible solution
index.php
PHP
<?php
function square(int $n): int
{
    return $n * $n;
}

echo square(9);
Output
OUTPUT
81