Manipulating the Data in Arrays


You can do even more with the data in arrays. For example, if you want to delete duplicate elements, you can use array_unique:

 <?php     $scores = array(65, 60, 70, 65, 65);     print_r($scores);     $scores = array_unique($scores);     print_r($scores); ?> 

Here's what this script looks like when you run itnote that the duplicate elements are removed:

 Array (     [0] => 65     [1] => 60     [2] => 70     [3] => 65     [4] => 65 ) Array (     [0] => 65     [1] => 60     [2] => 70 ) 

Here's another useful array functionarray_sum, which adds all the values in an array:

 <?php     $scores = array(65, 60, 70, 64, 66);     echo "Average score = ", array_sum($scores) / count($scores); ?> 

In this case, we're finding the average student score from the $scores array:

 Average score = 65 

And here's another onethe array_flip function will flip an array's keys and values. You can see that at work in Example 3-4, phpflip.php.

Example 3-4. Flipping an array, phpflip.php
 <HTML>         <HEAD>             <TITLE>                 Flipping an array             </TITLE>         </HEAD>         <BODY>             <H1>                 Flipping an array             </H1>             <?php                 $local_fruits = array("fruit1" => "apple", "fruit2" =>                     "pomegranate", "fruit3" => "orange");                 foreach ($local_fruits as $key => $value) {                     echo "Key: $key; Value: $value<BR>";                 }                 echo "<BR>";                 $local_fruits = array_flip($local_fruits);                 foreach ($local_fruits as $key => $value) {                     echo "Key: $key; Value: $value<BR>";                 }             ?>     </BODY> </HTML> 

The results appear in Figure 3-4note that the keys and values were indeed flipped.

Figure 3-4. Flipping an array.




    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