Returning Arrays from Functions


What about getting a function to return a whole array of values? No problem in PHP; the return statement can return arrays as easily as simple values.

For example, say you need a function that doubles the values in an array named array_doubler. You'd start by passing an array to this new function:

 function array_doubler($arr) {         .         .         . } 

In the body of the function, you can loop over all elements, doubling them and storing them back in the array that's been passed to the function like this:

 function array_doubler($arr) {     for($loop_index = 0; $loop_index < count($arr); $loop_index++){         $arr[$loop_index] *= 2;     }         .         .         . } 

Finally, you just return the doubled array as you would any other value:

 function array_doubler($arr) {     for($loop_index = 0; $loop_index < count($arr); $loop_index++){         $arr[$loop_index] *= 2;     }     return $arr; } 

You can see how using this function works in Example 4-6, phpdoubler.php, where we're passing an array to a functionand returning the array with each element doubled as well.

Example 4-6. Returning arrays from functions, phpdoubler.php
 <HTML>         <HEAD>             <TITLE>                 Return arrays from functions             </TITLE>         </HEAD>         <BODY>             <H1>                 Return arrays from functions             </H1>             <?php                 $array = array(1, 2, 3, 4, 5, 6);                 $array = array_doubler($array);                echo "Here are the doubled values;<BR>";                 foreach ($array as $value) {                     echo "Value: $value<BR>";                 }                 function array_doubler($arr)                 {                     for($loop_index = 0; $loop_index < count($arr);                         $loop_index++){                         $arr[$loop_index] *= 2;                     }                     return $arr;                 }         ?>     </BODY> </HTML> 

In phpdoubler.php, we're passing an array with the elements 1, 2, 3, 4, 5, and 6; doubler doubles each element and returns the array, as you see in Figure 4-6.

Figure 4-6. Returning arrays from functions.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net