start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

6.8. Returning More Than One Value

6.8.1. Problem

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

6.8.2. Solution

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

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

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

6.8.3. 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 global variables, but this clutters the global namespace and also makes it difficult to easily see which variables are being silently modified in the function. For example:

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

time_parts('12:34:56');

Again, here it's clear because the function is directly above the call, but if the function is in a different file or written by another person, it'd be more mysterious and thus open to creating a subtle bug.

Our advice is that if you modify a value inside a function, return that value and assign it to a variable unless you have a very good reason, such as significant performance issues. It's cleaner and easier to understand and maintain.

6.8.4. See Also

Recipe 6.4 on passing values by reference and Recipe 6.12 for information on variable scoping.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.