How to Return Multiple Values from a PHP Function
In PHP, a function can only return a single value using the
return statement. However, you can easily bypass this
limitation by returning data structures like arrays or objects, or by
using pass-by-reference variables. This article provides a quick,
practical guide on the most effective ways to return multiple values
from your PHP functions, complete with clear code examples.
1. Returning an Array
The most common and straightforward way to return multiple values is by wrapping them in an array. You can use either an indexed array or an associative array.
function getUserData() {
$name = "John Doe";
$email = "john@example.com";
$age = 30;
// Returning an associative array
return [
'name' => $name,
'email' => $email,
'age' => $age
];
}
$user = getUserData();
echo $user['name']; // Outputs: John Doe
echo $user['email']; // Outputs: john@example.com2. Using Array Destructuring
If you return an array, you can use PHP’s array destructuring syntax
([] or the older list() function) to
immediately assign the returned values to individual variables.
function getCoordinates() {
$latitude = 40.7128;
$longitude = -74.0060;
return [$latitude, $longitude];
}
// Destructuring the returned array into separate variables
[$lat, $lon] = getCoordinates();
echo $lat; // Outputs: 40.7128
echo $lon; // Outputs: -74.00603. Returning an Object
For more complex data or when you need type safety, returning an
object is a highly structured approach. You can use a generic standard
class (stdClass) or define a custom class.
class ConnectionResult {
public bool $success;
public string $message;
public function __construct(bool $success, string $message) {
$this->success = $success;
$this->message = $message;
}
}
function connectToDatabase(): ConnectionResult {
// Database connection logic...
return new ConnectionResult(true, "Connected successfully.");
}
$result = connectToDatabase();
if ($result->success) {
echo $result->message; // Outputs: Connected successfully.
}4. Using Pass-by-Reference
Another way to get multiple values back from a function is by passing
arguments by reference using the ampersand (&) symbol.
This allows the function to modify the original variables passed into
it.
function calculateStats($num1, $num2, &$sum, &$difference) {
$sum = $num1 + $num2;
$difference = $num1 - $num2;
}
$total = 0;
$diff = 0;
// The variables $total and $diff are modified directly
calculateStats(15, 5, $total, $diff);
echo $total; // Outputs: 20
echo $diff; // Outputs: 10