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

Web Technologies-I



                   Notes         //                              [0] => Three
                                 //                              [1] => Four )
                                 //                               )
                                 ?>

                                 6.4.2 Combine an Array with Data Elements and the Other with its Keys
                                 We can create an array by combining one array with keys and a second array with corresponding
                                 data elements. Note that the number of keys and data elements in both the arrays has to be
                                 equal for this operation to be successful. We will make use of built-in function array_combine().
                                 Its syntax is:
                                 array_combine ( array keys, array values )

                                 and the example using array_combine() is:
                                        Example:

                                 <?php

                                 $keys_array = array(1,2,3,4);
                                 $data_array = array(“one”,”two”,”three”,”four”);
                                 $new_array = array_combine($keys_array, $data_array);


                                 print_r($new_array);
                                 //Output: Array
                                 // (
                                 //     [1]  => one
                                 //     [2]  => two

                                 //     [3]  => three
                                 //     [4]  => four
                                 // )

                                 ?>
                                 6.4.3 Merging Two or More Arrays

                                 Using a built-in function array_merge() we can merge two or more arrays to form a single array.
                                 The values from the second array are appended at the end of the first array and so on. So, if three
                                 arrays are to be merged, elements from third will be appended at the end of the second array
                                 and then it will be appended at the end of the first array. Take a look at this syntax and example:
                                 array_merge ( array array1 [, array array2 [, array ...]] )

                                        Example:

                                 <?php
                                 $first_array = array(1,2);
                                 $second_array = array(3,4);
                                 $third_array = array(5,6);


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