6.7. Returning More Than One Value

Problem

You want to return more than one value from a function.

Solution

Return an array and use list( ) to separate elements:

function averages($stats) {
    ...
    return array($median, $mean, $mode);
}

list($median, $mean, $mode) = averages($stats);

Discussion

From a performance perspective, this isn’t a great idea. There is a bit of overhead because PHP is forced to first create an array and then dispose of it. That’s what is happening in this example:

function time_parts($time) {
    return explode(':', $time);
}

list($hour, $minute, $second) = time_parts('12:34:56');

You pass in a time string as you might see on a digital clock and call explode( ) to break it apart as array elements. When time_parts( ) returns, use list( ) to take each element and store it in a scalar variable. Although this is a little inefficient, the other possible solutions are worse because they can lead to confusing code.

One alternative is to pass the values in by reference. However, this is somewhat clumsy and can be nonintuitive since it doesn’t always make logical sense to pass the necessary variables into the function. For instance:

function time_parts($time, &$hour, &$minute, &$second) {
    list($hour, $minute, $second) = explode(':', $time);
}

time_parts('12:34:56', $hour, $minute, $second);

Without knowledge of the function prototype, there’s no way to look at this and know $hour, $minute, and $second are, in essence, the return values of time_parts( ).

You can also use

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.