PHP array_merge() Function
Merges two arrays into one array:
Example :
1 2 3 4 5 6 7 8 | <?php $A1=array("apple","papaya"); $A2=array("banana","grapes"); print_r(array_merge($A1,$A2)); ?> Output would be : Array ( [0] => apple[1] => papaya[2] => banana [3] => grapes ) |
1 | array_merge(array1,array2,array3...); |
Description
The array_merge() function merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the arrays have the same string keys then the later value of that key would override the previous one. If the arrays contains the numeric keys, the later value will not override the original value, but will be appended.
Array values with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
Example :
1. Array with numeric key
1 2 3 4 5 6 | < ?php $A=array(3=>"apple",4=>"papaya"); print_r(array_merge($A)); ?> output : Array ( [0] => apple [1] => papaya ) note : Here array keys is renumbered. |
2. If arrays has the same keys
1 2 3 4 5 6 7 8 | < ?php $A1=array("a"=>"apple","b"=>"grapes"); $A2=array("c"=>"banana","b"=>"papaya"); print_r(array_merge($A1,$A2)); ?> output : Array ( [a] => apple [b] => papaya [c] => banana ) Note : Here later key value override the previous one. |
Merge two arrays in php is common requirement and array_merge() is the handy function for this purpose