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

Unit 7: Functions



            $person[“age group”] = “Old”;                                                         Notes
            } else {

            $person[“age group”] = “Young”;
            }

            }
            print_r($people);

            Again, this code makes use of the print_r() function.
            The output of the previous code is the following:

            Array
            (

            [1] => Array
            (

            [name] => Peter
            [age] => 28

            [age group] => Young
            )

            [2] => Array
            (

            [name] => Barbara
            [age] => 67

            [age group] => Old
                       )

            )
            You can see that both the Peter and Barbara arrays inside the $people array were added an
            additional value with their respective age group.

            7.8.7 Traversing Arrays Using List( ) and Each( )
            Although foreach() is the nicer way of iterating over an array, an additional way of traversing
            an array is by using a combination of the list( ) construct and the each( ) function:

            $players = array(“Peter”, “Barbara”, “Bill”, “Nancy”);

            reset($players);
            while (list($key, $val) = each($players)) {

            print “#$key = $val\n”;
            }



                                             LOVELY PROFESSIONAL UNIVERSITY                                   117
   117   118   119   120   121   122   123   124   125   126   127