Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 it—note 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 function—array_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 one—the 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-4—note that the keys and values were indeed flipped.

03fig04.gif

Figure 3-4 Flipping an array.

  • + Share This
  • 🔖 Save To Your Account