Returning arrays from functions is one way to return multiple values from a single function call, but there's anotheryou can return a list. This is a handy way of returning multiple values from a single function call. We can use the same function, array_doubler, as in the previous chunk: function array_doubler($arr) { for($loop_index = 0; $loop_index < count($arr); $loop_index++){ $arr[$loop_index] *= 2; } return $arr; } This function is passed an array. It doubles each element's value in the array and returns that array. When that array is returned, you can assign it to a list of variables like this: list($first, $second, $third, $fourth, $fifth, $sixth) = array_doubler($array); This assigns the first element of the array to $first, the second element to $second, and so on. All that's left is to echo the values of $first, $second, and so on, as you see in phplist.php, Example 4-7. Example 4-7. Returning lists from functions, phplist.php<HTML> <HEAD> <TITLE> Return lists from functions </TITLE> </HEAD> <BODY> <H1> Return lists from functions </H1> <?php $array = array(1, 2, 3, 4, 5, 6); list($first, $second, $third, $fourth, $fifth, $sixth) = array_doubler($array); echo "\$first: $first<BR>"; echo "\$second: $second<BR>"; echo "\$third: $third<BR>"; echo "\$fourth: $fourth<BR>"; echo "\$fifth: $fifth<BR>"; echo "\$sixth: $sixth<BR>"; function array_doubler($arr) { for($loop_index = 0; $loop_index < count($arr); $loop_index++){ $arr[$loop_index] *= 2; } return $arr; } ?> </BODY> </HTML> The results appear in Figure 4-7, where, as you see, we've been able to assign the various array elements to the variables $first, $second, $third, and so on. Figure 4-7. Returning lists from functions.What if you only wanted, say, the first three elements of the returned array? You could do something like this, ignoring the last three elements: list($first, $second, $third) = array_doubler($array); echo "\$first: $first\n"; echo "\$second: $second\n"; echo "\$third: $third\n"; No problem at all. Note, however, that you can't directly return a list from a function like this: return list($arr[0], $arr[1], $arr[2], $arr[3], $arr[4], $arr[5]); //Won't work! |