November 23, 2026 - 09:43
PHP Lesson 12 — echo vs return: Where Does the Value Go? Image
PHP Tutorials

PHP Lesson 12 — echo vs return: Where Does the Value Go?

0 Comments

A function prints the right number, but assigning its result to a variable gives you NULL. How can the value be missing when you just saw 150 on screen? This is a good place to separate echo from return.

echo produces output. In a terminal you see it immediately; in a web request it becomes part of the response. return ends the current function and passes a value back to the calling code. That code still decides whether the value should be displayed.

The number appears, but the variable is NULL

Create experiment.php in a new folder and run it there with php experiment.php. If you need to install PHP, start with the first lesson in the series.

PHP
<?php
function totalPrice(int $price, int $quantity)
{
    echo $price * $quantity;
}

$total = totalPrice(50, 3);
echo PHP_EOL;
var_dump($total);

You get 150 followed by NULL. During the call, the function's echo prints the multiplication result. The function then ends without returning a value, so the call evaluates to null. That is what gets assigned to $total. var_dump() lets us inspect both the type and value of the variable.

Seeing a value in the output does not prove that a function returned it. We are checking two different things: the output produced during the call and the value handed back by the call.

Let the calculation give us a number

Replace the file with this version. Inside the function we replace echo with return, and declare the integer return type with : int.

PHP
<?php
function totalPrice(int $price, int $quantity): int
{
    return $price * $quantity;
}

$total = totalPrice(50, 3);
var_dump($total);

echo "Payable: ", $total - 20, PHP_EOL;

Now you get int(150) and Payable: 130. Because the number is stored in a variable, we can subtract a discount. We could also use it in another calculation or display it elsewhere. Printing the number inside the function did not provide that return value.

PHP_EOL adds a newline to terminal output. A browser needs HTML structure, such as paragraphs, to display separate blocks; the constant does not create a new HTML paragraph by itself.

I used return, and now nothing appears

PHP
<?php
function totalPrice(int $price, int $quantity): int
{
    return $price * $quantity;
}

totalPrice(50, 3);
echo "The script continued", PHP_EOL;

This version only prints The script continued. The function calculated and returned 150, but we neither stored nor printed that result. Add echo totalPrice(50, 3), PHP_EOL; before the final line to display it. Returning is not an instruction to print.

The template syntax <?= $total ?> is a short form of echo. It inserts a value at that point in the HTML. It does not perform a separate calculation or validate the value.

return is also the function's exit door

PHP
<?php
function titleError(string $title): ?string
{
    if (trim($title) === '') {
        return 'Write a title';
    }

    return null;
}

var_dump(titleError('   '));
var_dump(titleError('Read the lesson'));

echo "The script continued", PHP_EOL;

The first call passes three spaces. After trim() removes them, the title is empty and the function returns its message immediately. That call never reaches return null;. The second call contains a title and does reach it.

?string means the return value may be a string or null. Our convention is that a string explains an error and null means this check found no error. Notice the final The script continued line after the message and NULL: the function ended, but the calling script continued. A return inside a function does not stop the entire application like exit.

Calculate in the function, display in the template

Bring that distinction back to the task list. In this standalone example we deliberately create boolean true/false values for done; we are not assuming database 0/1 values have the same type.

PHP
<?php
function remainingTasks(array $tasks): int
{
    $count = 0;

    foreach ($tasks as $task) {
        if ($task['done'] === false) {
            $count++;
        }
    }

    return $count;
}

$tasks = [
    ['title' => 'Read', 'done' => true],
    ['title' => 'Try', 'done' => false],
    ['title' => 'Change', 'done' => false],
];

$remaining = remainingTasks($tasks);
?>
<p>Remaining tasks: <?= $remaining ?></p>

For a browser test, run php -S 127.0.0.1:8001 in the folder and open http://127.0.0.1:8001/experiment.php. The paragraph says Remaining tasks: 2. The function only counts and returns a number. The template supplies the wording and HTML. If you display a user-supplied title instead of this integer count, encode it for HTML with htmlspecialchars().

Change the last task's false to true and refresh. The count should drop to 1 without changing the paragraph template. That small edit shows what separating calculation from presentation buys us.

Where this appeared in the task list: PHP Lesson 04 — Organize the Code with Functions and Files

Official documentation: echo · return · Returning values

Related Articles

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment