← Back to all snippets
PHP

Merge Arrays with Different Key Handling Strategies

Understand how to combine multiple PHP arrays using `array_merge` for re-indexed numeric keys or the `+` operator for preserving associative keys during merging.

<?php
$array1 = ['a' => 1, 'b' => 2];
$array2 = ['c' => 3, 'a' => 4];

// Using array_merge(): Numeric keys are re-indexed, string keys overwrite
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);
/* Output:
Array
(
    [a] => 4
    [b] => 2
    [c] => 3
)
*/

$indexedArray1 = [1, 2, 3];
$indexedArray2 = [4, 5, 6];
$mergedIndexed = array_merge($indexedArray1, $indexedArray2);
print_r($mergedIndexed);
/* Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
*/

// Using the + operator: First array's keys are prioritized
// Numeric keys are NOT re-indexed, if keys conflict, first array's value is kept
$combinedArray = $array1 + $array2;
print_r($combinedArray);
/* Output:
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)
*/

$indexedCombined = $indexedArray1 + $indexedArray2;
print_r($indexedCombined);
/* Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
(Note: elements from indexedArray2 are not added because keys 0,1,2 already exist)
*/
How it works: PHP offers different ways to merge arrays, each with distinct behavior. `array_merge()` combines elements from one or more arrays, re-indexing numeric keys and overwriting string keys if duplicates exist (later arrays take precedence). The `+` operator, however, prioritizes the keys from the left-hand array; it only adds key-value pairs from the right-hand array if the keys do not already exist in the left-hand array. This distinction is crucial when deciding how to handle duplicate keys and maintain original numeric indices.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs