In PHP development, it’s common to need to merge several arrays into a larger array for easier data processing. The built-in array_merge function is designed precisely for this purpose.
The array_merge function accepts multiple arrays as arguments and merges them into a new array. The basic syntax is:
array_merge(array $array1 [, array $... ]) : array
Here, $array1 is the first required array to merge, followed by optional additional arrays.
$fruits = array('apple', 'banana', 'cherry'); $vegetables = array('carrot', 'broccoli', 'cabbage'); <p>$combinedArray = array_merge($fruits, $vegetables);</p> <p>print_r($combinedArray);<br>
The output is:
Array ( [0] => apple [1] => banana [2] => cherry [3] => carrot [4] => broccoli [5] => cabbage )
As shown, the elements from both arrays are merged sequentially into a new array.
If the arrays contain string keys, array_merge overwrites values of matching keys from earlier arrays with values from later arrays. Numeric keys will be re-indexed to continuous numbers.
$array1 = array('a' => 'apple', 'b' => 'banana'); $array2 = array('b' => 'broccoli', 'c' => 'carrot'); <p>$combinedArray = array_merge($array1, $array2);</p> <p>print_r($combinedArray);<br>
The output:
Array ( [a] => apple [b] => broccoli [c] => carrot )
Here, the key 'b' is overwritten by the value from the second array.
array_merge is a highly useful function in PHP for simplifying the handling of multiple arrays. Understanding its behavior regarding key overwriting and index resetting helps you write more stable and efficient code.