Return Values
A function can send a value back to the code that called it.
Syntax
function name(): type {
return value;
}Use the return keyword to send a result back from a function. Once return runs, the function stops immediately.
You can declare the return type after the parentheses with : type.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Return the generated auth token string from a createToken() function for the caller to store in the session.
- Return an array of validation errors from a validateForm() function so the controller can decide what to display.
- Return null from a findById() function when the record does not exist in the database.
More examples
Returning a scalar value
The return statement sends a computed value back to the caller; declaring the return type adds a safety contract.
<?php
function fahrenheitToCelsius(float $f): float {
return ($f - 32) * 5 / 9;
}
$c = fahrenheitToCelsius(98.6);
echo round($c, 1); // 37.0Returning an array of results
Returning an array lets a function communicate multiple results at once, here collecting all validation failures.
<?php
function validateEmail(string $email): array {
$errors = [];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email format.';
}
if (strlen($email) > 255) {
$errors[] = 'Email too long.';
}
return $errors;
}
$errors = validateEmail('bad-email');
if ($errors) {
print_r($errors);
}Early return for guard clauses
Early returns handle invalid or simple cases at the top, keeping the main logic unindented and easier to read.
<?php
function getDiscount(int $userId, float $price): float {
if ($userId <= 0) {
return 0.0; // invalid user
}
$isPremium = ($userId % 2 === 0); // simplified check
if (!$isPremium) {
return 0.0;
}
return round($price * 0.15, 2); // 15% discount
}
echo getDiscount(2, 100.00); // 15.0
Discussion