Page 163 - Open Soource Technologies 304.indd
P. 163

Unit 7: Multidimensional Arrays



            end( )                                                                                Notes
            Moves the iterator to the last element in the array and returns it
            each( )
            Returns the key and value of the current element as an array and moves the iterator to the next
            element in the array
            key( )
            Returns the key of the current element
            The each( ) function is used to loop over the elements of an array. It processes elements according
            to their internal order:
            reset($addresses);
            while (list($key, $value) = each($addresses))
            {

            echo “$key is $value<BR>\n”;
            }
            Output:

            0 is spam@cyberpromo.net 1 is abuse@example.com
            This approach does not make a copy of the array, as foreach does. This is useful for very large
            arrays when you want toconserve memory.
            The iterator functions are useful when you need to consider some parts of the array separately
            from others. Example shows code that builds a table, treating the first index and value in an
            associative array as table column headings.
                          Building a table with the iterator functions

            $ages = array (‘Person’ => ‘Age’,
             ‘Pradip’ => 35, ‘Barney’ => 30,
            ‘Tigger’ => 8, ‘Pooh’ => 40);

            // start table and print heading reset ($ages);
            list($c1, $c2) = each($ages);
             echo(“<table><tr><th>$c1</th><th>$c2</th></tr>\n”);

            // print the rest of the values
            while (list($c1,$c2) = each($ages)) {
            echo(“<tr><td>$c1</td><td>$c2</td></tr>\n”);
            } // end the table
            echo (“</table>”);

             <table>
            <tr><th>Person</th><th>Age</th></tr>
            <tr><td>Pradip</td><td>35</td></tr>
             <tr><td>Barney</td><td>30</td></tr>

             <tr><td>Tigger</td><td>8</td></tr>


                                             LOVELY PROFESSIONAL UNIVERSITY                                   157
   158   159   160   161   162   163   164   165   166   167   168