PHP Return Values
In this page:
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
function add($a, $b) {
return $a + $b;
echo "This never runs";
}
echo add(2, 3);
?>
Login to try C/C++/Java/PHP code in the editor
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
function getName() {
return ["Alice", "Smith"];
}
[$first, $last] = getName();
echo "$first $last";
?>
Login to try C/C++/Java/PHP code in the editor
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
function add(int $a, int $b): int {
return $a + $b;
}
echo add(2, 3);
?>
Login to try C/C++/Java/PHP code in the editor
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
function findUser(bool $exists): ?string {
return $exists ? "Alice" : null;
}
var_dump(findUser(false));
?>
Login to try C/C++/Java/PHP code in the editor
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
function logMessage(string $msg): void {
echo "LOG: $msg";
}
logMessage("Saved successfully");
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: