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

Unit 7: Multidimensional Arrays



            function reverseCompare($x, $y)                                                       Notes
            {
            if ( $x[2] == $y[2] )

             return 0;
            else if ( $x[2] < $y[2] )

             return 1;
            else
             return -1;
            }

            Calling usort($products, reverse Compare) would now result in the array being placed in
            descending order by price.

                          The  user-defined  sorts  do  not  have  reverse  variants,  but  you  can  sort  a
                          multidimensional array into reverse order by the comparison function.

            7.6 Acting on Entire Arrays

            PHP has several useful functions for modifying or applying an operation to all elements of an
            array. You can merge arrays, find the difference, calculate the total, and more, all using built-in
            functions.
            7.6.1 Merging Two Arrays

            The array_merge( ) function intelligently merges two or more arrays:
            $merged = array_merge(array1, array2 [, array ... ])
            If a numeric key from an earlier array is repeated, the value from the later array is assigned a
            new numeric key:
            $first = array(‘hello’, ‘world’); // 0 => ‘hello’, 1 => ‘world’ $second = array(‘exit’, ‘here’); // 0
            => ‘exit’, 1 => ‘here’
            $merged = array_merge($first, $second); // $merged = array(‘hello’, ‘world’, ‘exit’, ‘here’)
            If a string key from an earlier array is repeated, the earlier value is replaced by the later value:

            $first = array(‘bill’ => ‘clinton’, ‘tony’ => ‘danza’);
            $second = array(‘bill’ => ‘gates’, ‘adam’ => ‘west’);
            $merged = array_merge($first, $second); // $merged = array(‘bill’ => ‘gates’, ‘tony’ => ‘danza’,
            ‘adam’ => ‘west’)
            7.6.2 Calculating the Sum of an Array

            The array_sum( ) function adds up the values in an indexed or associative array:
            $sum = array_sum(array);

            For example:
            $scores = array(98, 76, 56, 80); $total = array_sum($scores); // $total = 310






                                             LOVELY PROFESSIONAL UNIVERSITY                                   163
   164   165   166   167   168   169   170   171   172   173   174