user2065501 user2065501 - 2 months ago 8x
PHP Question

Returning multiple values: Return array vs change referenced parameters

When I need to return multiple values as result of my function (For example, let's say a boolean stating if a specific operation was successful, and a message stating the error or success message), should I return those multiple values in an array, or by making the function arguments be references and change their value?

function myFunction($input){
return array("success" => true/false, "message" => "Internal Error"/"Success");


function myFunction($input, &$success, &$message){
$success = true;
$message = "It worked";

What would be considered best practice? I've already seen both in various codebases, even in other languages.


It really depends on your use-case and what suits your need the best. Both methods can be used, while the second methods is used by some built-in PHP functions (e.g. exec). If you don't need an array from the beginning since you don't output it (e.g. as JSON), you should go with references and might just return true or false depending on the successful completion or not. If you once need the message, you can then just use the variable you referenced.

function myFunction($input, &$return_message) {
    if($input ...) {
        $return_message = 'action 1 successfully';
        return true;
    } else {
        $return_message = 'invalid input';

    return false;

$msg = "";
$action = myFunction(array('Hello'), $msg);
if($action === true) {
    echo 'Action completed!';
} else {
    die('Action not successfully, error message: '.$msg);