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

Unit 6: Arrays



             $merged_array = array_merge($first_array,$second_array,$third_array);                Notes

            print_r($merged_array);
            //Output: Array
            //          ( [0] => 1
            //            [1] => 2
            //            [2] => 3
            //            [3] => 4
            //            [4] => 5
            //            [5] => 6
            //          )
             ?>
            6.4.4 Searching for a Value in an Array
            Searching for a value in an array is made simple using the function array_search(). If the keyword
            is found in the array, then the corresponding key of that value is retured for further operations.
            The syntax and example are:
            array_search ( keyword, array name )
            <?php


            $months = array(1=>”Jan”, “Feb”, “Mar”, “Apr”, “May”, “June”, “July”, “Aug”,
            “Sep”, “Oct”, “Nov”, “Dec”);

            $key = array_search(“May”, $months); //Searching for May in months array

            echo $key;
            // We can also print the value that key points at

            echo $months[$key];

            ?>


            6.4.5 Sorting Arrays

            It is often useful to sort related data stored in an array. Taking a one-dimensional array and
            sorting it into order is quite easy.

            Using sort()
            The following code results in the array being sorted into ascending alphabetical order:

            $products = array( ‘Tires’, ‘Oil’, ‘Spark Plugs’ );
            sort($products);
            Our array elements will now be in the order Oil, Spark Plugs, Tires.




                                             LOVELY PROFESSIONAL UNIVERSITY                                   139
   140   141   142   143   144   145   146   147   148   149   150