Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: returning multiple values

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.

like image 327
Emanuel Lainas Avatar asked Jun 16 '15 15:06

Emanuel Lainas


People also ask

Can return have multiple values?

Summary. JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.

Is it a good practice to return multiple values in Python?

It's fine to return multiple values using a tuple for simple functions such as divmod . If it makes the code readable, it's Pythonic. If the return value starts to become confusing, check whether the function is doing too much and split it if it is. If a big tuple is being used like an object, make it an object.

Can you return multiple values from a function at a time?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.


1 Answers

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
like image 69
pkshultz Avatar answered Sep 30 '22 07:09

pkshultz