PHP

Merge Multiple Arrays Efficiently

Learn to combine multiple PHP arrays using `array_merge` for indexed arrays and the `+` operator for associative arrays, handling duplicate keys effectively.

<?php

// Example 1: Merging indexed arrays using array_merge
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$mergedIndexed = array_merge($array1, $array2);
// Result: [1, 2, 3, 4, 5, 6]

// Example 2: Merging associative arrays with array_merge (values overwritten for duplicate keys)
$assoc1 = ['a' => 1, 'b' => 2];
$assoc2 = ['b' => 3, 'c' => 4];
$mergedAssocArrayMerge = array_merge($assoc1, $assoc2);
// Result: ['a' => 1, 'b' => 3, 'c' => 4]

// Example 3: Merging associative arrays with the + operator (keys from first array preserved for duplicates)
$mergedAssocPlus = $assoc1 + $assoc2;
// Result: ['a' => 1, 'b' => 2, 'c' => 4]

echo "Merged Indexed: " . json_encode($mergedIndexed) . "
";
echo "Merged Associative (array_merge): " . json_encode($mergedAssocArrayMerge) . "
";
echo "Merged Associative (+ operator): " . json_encode($mergedAssocPlus) . "
";

?>
How it works: This snippet demonstrates two primary ways to merge arrays in PHP. `array_merge()` combines elements, re-indexing numeric keys and overwriting values for duplicate string keys from later arrays. The `+` operator, specifically for associative arrays, merges arrays by preserving the values from the first array encountered if keys are duplicated, and only adding new key-value pairs from subsequent arrays.

Need help integrating this into your project?

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

Hire DigitalCodeLabs