Best practice: returning multiple values

6.1k views Asked by At

What would be recommended from a pure coding best practices perspective to adopt as a standard for medium-large developer teams?

Return a sequential array:

function get_results($filter) {
    $query = "SELECT SQL_CALC_FOUND_ROWS, * FROM ...";

    $results = ...
    $total = ...

    return array($results, $total);
}

Return an associative array:

function get_results($filter) {
    $query = "SELECT SQL_CALC_FOUND_ROWS, * FROM ...";

    $results = ...
    $total = ...

    return array(
        'resuts' => $results, 
        'total' => $total
    );
}

Return single result and assign the second by reference (?!):

function get_results($filter, &$count = null) {
    $query = "SELECT SQL_CALC_FOUND_ROWS, * FROM ...";

    $results = ...
    $total = ...

    $count = $total;
    return $results;
}

Feel free to suggest any other approach.

1

There are 1 answers

0
pkshultz On

From the PHP documentation:

A function can not return multiple values, but similar results can be obtained by returning an array.

All of these seem like good practices given what the documentation states. A comment in the documentation reveals one other way: using list(). See the example below:

function fn($a, $b)
{
   # complex stuff

    return array(
      $a * $b,
      $a + $b,
   );
}

list($product, $sum) = fn(3, 4);

echo $product; # prints 12
echo $sum; # prints 7