xi-mfw
Last Updated: February 25, 2016
·
864
· rican7
08 16 2009   niantic boardwalk  3   square

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?

Say Thanks
Respond

3 Responses
Add your response

12122
Me

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 ·
12127
D3b2094f1b3386e660bb737e797f5dcc

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

over 1 year ago ·
12128
08 16 2009   niantic boardwalk  3   square

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

over 1 year ago ·