Passing Arrays to Functions


Besides data such as simple variables, you can also pass arrays to functions with no extra work. Here's an example, where we're creating a function named array_echoer that simply echoes the contents of an array:

 <?php     $fruits[0] = "pineapple";     $fruits[1] = "pomegranate";     $fruits[2] = "tangerine";     $fruits[3] = "watermelon";     array_echoer($fruits);     function array_echoer($array)     {         for ($index = 0; $index < count($array); $index++){             echo "Element $index: ", $array[$index], "\n";         }     } ?> 

Here are the results:

 Element 0: pineapple Element 1: pomegranate Element 2: tangerine Element 3: watermelon 

Here's another example where we're averaging student test scores that are held in an array:

 <?php     $test_scores[0] = 98;     $test_scores[1] = 36;     $test_scores[2] = 54;     $test_scores[3] = 64;     array_averager($test_scores);     function array_averager($scores)     {         $total = 0;         for ($index = 0; $index < count($scores); $index++){             $total += $scores[$index];         }         echo "Average score = ", $total / count($scores);     } ?> 

Here's what you see from this script:

 Average score = 63 



    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