PHP
Efficiently Merge Multiple PHP Arrays
Learn how to combine multiple PHP arrays into a single array using the `array_merge()` function, perfect for consolidating data from various sources while handling different key types.
<?php
$array1 = ['a' => 1, 'b' => 2];
$array2 = ['c' => 3, 'a' => 4]; // 'a' will be overwritten by array2's 'a'
$array3 = [5, 6, 7];
$mergedArray = array_merge($array1, $array2, $array3);
print_r($mergedArray);
/*
Output:
Array
(
[a] => 4
[b] => 2
[c] => 3
[0] => 5
[1] => 6
[2] => 7
)
*/
// For numeric keys, values are appended and re-indexed:
$numArray1 = [1, 2, 3];
$numArray2 = [4, 5, 6];
$mergedNumArray = array_merge($numArray1, $numArray2);
print_r($mergedNumArray);
/*
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
*/
?>
How it works: `array_merge()` combines one or more arrays. For associative arrays, if identical string keys exist, the latter array's value overwrites the former's. For numeric arrays, values are appended, and keys are re-indexed numerically starting from zero. This function is ideal for consolidating data from various sources into a single coherent structure.