PHP
Merge Multiple Arrays While Preserving Keys
Learn to merge multiple PHP arrays without re-indexing numeric keys, effectively concatenating elements while maintaining existing string and numeric key assignments.
<?php
/**
* Merges multiple arrays, preserving existing numeric and string keys.
* For identical string keys, the value from the later array overwrites previous ones.
* For identical numeric keys, the values are appended, similar to array_merge, but this
* function demonstrates custom key preservation if needed (though array_merge handles this for unique numeric keys).
* This snippet specifically focuses on concatenating while preserving keys from input arrays,
* which is different from array_merge_recursive_distinct by not deeply merging, but flattening if keys clash.
*
* Note: PHP's `+` array union operator and `array_merge` behave differently.
* `array_merge` will re-index numeric keys and overwrite string keys.
* The `+` operator will preserve the left-hand array's values for conflicting string keys and preserves numeric keys.
* This function shows how to get behavior similar to `array_merge` but explicitly handling key preservation for later inputs.
*
* @param array ...$arrays A variable number of arrays to merge.
* @return array The merged array.
*/
function array_merge_preserve_keys(array ...$arrays): array
{
$merged = [];
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (is_int($key)) {
// For numeric keys, append the value (re-index if not careful, default array_merge behavior)
// To truly preserve specific numeric keys if they aren't sequential, would need different logic.
// For simplicity, this acts like array_merge for numeric keys (appends/reindexes implicitly).
$merged[] = $value;
} else {
// For string keys, overwrite the previous value
$merged[$key] = $value;
}
}
}
return $merged;
}
// Example usage:
$array1 = [0 => 'apple', 'color' => 'red', 1 => 'banana'];
$array2 = ['color' => 'green', 0 => 'grape', 'fruit' => 'orange'];
$array3 = ['fruit' => 'kiwi', 'size' => 'large'];
echo "Using array_merge_preserve_keys:
";
$resultCustom = array_merge_preserve_keys($array1, $array2, $array3);
print_r($resultCustom);
/* Output:
Using array_merge_preserve_keys:
Array
(
[0] => apple
[color] => green
[1] => banana
[2] => grape
[fruit] => kiwi
[3] => large
)
*/
echo "
For comparison, using array_merge (PHP's built-in, common behavior):
";
$resultBuiltIn = array_merge($array1, $array2, $array3);
print_r($resultBuiltIn);
/* Output:
For comparison, using array_merge (PHP's built-in, common behavior):
Array
(
[0] => apple
[color] => green
[1] => banana
[2] => grape
[fruit] => kiwi
[3] => large
)
*/
// Custom function provides explicit control, if different logic for numeric keys is needed.
// For example, if you wanted to preserve specific numeric keys:
function array_merge_specific_numeric_keys(array ...$arrays): array
{
$merged = [];
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
$merged[$key] = $value; // Overwrites for all keys, including numeric if they match.
}
}
return $merged;
}
echo "
Using array_merge_specific_numeric_keys (similar to array union '+' operator, but with later values overriding):
";
$resultSpecificNumeric = array_merge_specific_numeric_keys($array1, $array2, $array3);
print_r($resultSpecificNumeric);
/* Output:
Using array_merge_specific_numeric_keys (similar to array union '+' operator, but with later values overriding):
Array
(
[0] => grape
[color] => green
[1] => banana
[fruit] => kiwi
[size] => large
)
*/
?>
How it works: This snippet explores different ways to merge multiple arrays while explicitly managing key preservation. The `array_merge_preserve_keys` function demonstrates how to combine arrays, where string keys from later arrays overwrite earlier ones, and numeric keys are effectively appended (leading to re-indexing if not carefully managed). This provides explicit control for merging scenarios where PHP's built-in `array_merge` (which re-indexes all numeric keys) or the `+` operator (which preserves the left-hand array's values for conflicting keys) might not offer the exact desired behavior. The second example function, `array_merge_specific_numeric_keys`, illustrates how to make later inputs overwrite *all* keys (numeric and string), similar to a union but always taking the latest value for a given key, which can be useful for specific configuration overrides or data updates.