In PHP, there are several methods to merge two arrays. The method you choose depends on the behavior you want (e.g. preserving keys, reindexing, handling duplicate keys, etc.). Here are the most common methods:
1. Using array_merge()
- Combines two or more arrays.
- Numeric keys are reindexed.
- String keys are overwritten by the later array.
1 2 3 |
$a = [1, 2, 3]; $b = [4, 5]; $result = array_merge($a, $b); // [1, 2, 3, 4, 5] |
1 2 3 |
$a = ["a" => 1, "b" => 2]; $b = ["b" => 3, "c" => 4]; $result = array_merge($a, $b); // ["a" => 1, "b" => 3, "c" => 4] |
2. Using +
(Union operator)
- Preserves keys.
- If a key exists in the first array, it is not overwritten by the second.
1 2 3 |
$a = ["a" => 1, "b" => 2]; $b = ["b" => 3, "c" => 4]; $result = $a + $b; // ["a" => 1, "b" => 2, "c" => 4] |
3. Using array_merge_recursive()
- Similar to
array_merge()
, but merges values with the same string keys into arrays.
1 2 3 4 |
$a = ["a" => 1, "b" => 2]; $b = ["b" => 3, "c" => 4]; $result = array_merge_recursive($a, $b); // ["a" => 1, "b" => [2, 3], "c" => 4] |
4. Using the Spread Operator (PHP 7.4+)
- Only works with numeric keys and reindexes them.
1 2 3 |
$a = [1, 2]; $b = [3, 4]; $result = [...$a, ...$b]; // [1, 2, 3, 4] |
5. Using array_replace()
- Similar to
array_merge()
but doesn’t reindex numeric keys.
1 2 3 |
$a = ["a" => 1, "b" => 2]; $b = ["b" => 3]; $result = array_replace($a, $b); // ["a" => 1, "b" => 3] |
6. Manual Looping
- For more customized merging logic.
1 2 3 4 5 6 |
$a = [1, 2]; $b = [3, 4]; foreach ($b as $value) { $a[] = $value; } // $a becomes [1, 2, 3, 4] |
If you let me know your use case (e.g. preserve keys, avoid duplicates), I can recommend the most suitable method.