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

Unit 6: Building Blocks of PHP



            print “ is of age “;                                                                  Notes
            print $person[“value”];

            This prints

            John is of age 28
            When we explain how the list() construct works, you will understand why offsets 0 and 1 also
            exist.

            list() The list() construct is a way of assigning multiple array offsets to multiple variables in
            one statement:

            list($var1, $var2, ...) = $array;

            The first variable in the list is assigned the array value at offset 0, the second is assigned offset 1,
            and so on. Therefore, the list() construct translates into the following series of PHP statements:
            $var1 = $array[0];

            $var2 = $array[1];
            ...

            As previously mentioned, the indexes 0 and 1 returned by each() are used by the list() construct.
            You can probably already guess how the combination of list() and each() work. Consider the
            highlighted line from the previous $players traversal example:
            $players = array(“John”, “Barbara”, “Bill”, “Nancy”);

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

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

            }
            What happens in the boldfaced line is that during every loop iteration, each() returns the current
            position’s key/value pair array, which, when examined with print_r(), is the following array:

            Array
            (

            [1] => John

            [value] => John
            [0] => 0

            [key] => 0
            )

            Then, the list() construct assigns the array’s offset 0 to $key and offset 1

            to $val.



                                             LOVELY PROFESSIONAL UNIVERSITY                                    85
   85   86   87   88   89   90   91   92   93   94   95