Last Updated: February 25, 2016
·
1.062K
· rican7

What's your preferred method for returning multiple values?

I've seen a few different ways of trying to emulate a "tuple"-like return style in PHP. Luckily its possible in PHP, but there are a few different ways of doing so.

Here's an example:

$params_to_return = array(
    'count' => range(1,10),
    'sum' => array_sum(range(1,10))
);

// Manually
$count = $params_to_return['count'];
$sum = $params_to_return['sum'];

var_dump($count, $sum);
unset($count, $sum);

// Automatically
extract($params_to_return);

var_dump($count, $sum);
unset($count, $sum);

// Listing
list($count, $sum) = array_values($params_to_return);

var_dump($count, $sum);
unset($count, $sum);

(From https://gist.github.com/Rican7/8446462)

If you want to see how it behaves when executed, check here:
http://3v4l.org/0DGOb

What is your preferred way?

3 Responses
Add your response

I would like to test the performance of the functions but the cleaner I think is list...
But i think that normally a method shouldn't do something like that... *(Thinking in OOP...)
I think you should set some internals properties.

over 1 year ago ·

Shameless plug for golang... go natively supports multiple return values from a function.

over 1 year ago ·

@steve-Jansen yea, several languages do. Python does, etc., but that's far from the point isn't it?

over 1 year ago ·