← Back to PHP Course | Chapter 5: Functions | Lesson 3 of 10

PHP Return Values

Returning Values

return sends a value back to whatever code called the function, and execution of the function stops the instant return runs — any code written after it inside the same function never executes.

Example: Returning Values

php
<?php
function add($a, $b) {
    return $a + $b;
    echo "This never runs";
}
echo add(2, 3);
?>

Returning Multiple Values

A PHP function can only return one value directly, but you can bundle several related values into an array and return that instead — then unpack the array back into separate variables at the call site using list() or square-bracket destructuring.

Example: Returning Multiple Values

php
<?php
function getName() {
    return ["Alice", "Smith"];
}
[$first, $last] = getName();
echo "$first $last";
?>

Return Type Declarations

Adding : type after a function's closing parenthesis declares what type its return value must be. If the function's body tries to return something that doesn't match, PHP raises a TypeError — this catches a whole class of bugs at the source rather than wherever the mismatched value eventually causes trouble.

Example: Return Type Declarations

php
<?php
function add(int $a, int $b): int {
    return $a + $b;
}
echo add(2, 3);
?>

Nullable Return Types

Prefixing a return type with ? (function find(): ?User) marks it nullable, explicitly allowing the function to return either the declared type or null. Without that ?, returning null from a function typed to return User would trigger a type error.

Example: Nullable Return Types

php
<?php
function findUser(bool $exists): ?string {
    return $exists ? "Alice" : null;
}
var_dump(findUser(false));
?>

Void Return Type

A void return type is PHP's way of stating a function performs an action but deliberately produces no value to hand back — logging a message, say, or updating a database row. Trying to return an actual expression from inside a void function is a compile-time error, not just a style violation.

Example: Void Return Type

php
<?php
function logMessage(string $msg): void {
    echo "LOG: $msg";
}
logMessage("Saved successfully");
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.