How to Merge Arrays in PHP: Combine Array with array_merge
Sat Sep 6th, 2025 — 2 days ago

How to Merge Arrays in PHP

Working with arrays in PHP often requires combining data from multiple sources. Whether you want to merge indexed arrays, overwrite keys in associative arrays, or handle nested structures, PHP gives you several tools. The most common approaches are array_merge, array_replace, or using the union operator. In many cases you may just want to combine arrays directly, but in others you might need finer control like keeping keys intact or managing deep merges. Understanding how to merge arrays in PHP — and when to simply append values — helps avoid data loss and unexpected results.

Problem

how to merge arrays in PHP

  • Merge indexed arrays or associative arrays correctly.
  • Preserve or overwrite keys as needed.
  • Handle deep (nested) structures without surprises.

Solutions

  • Use array_merge() for most cases. It appends values and renumbers numeric keys.
  • Use the union operator + to preserve existing keys from the left array.
  • Use array_replace() to overwrite values by key without renumbering.
  • For nested data, prefer array_replace_recursive() over array_merge_recursive() if you want overwrite semantics.
  • To merge many arrays, pass them with the splat operator: array_merge(...$arrays).
<?php
// 1) Basic merge (numeric keys get renumbered)
$a = [10, 20];
$b = [30, 40];
$result = array_merge($a, $b);          // [10, 20, 30, 40]

// 2) Preserve keys from the left-hand array (no renumbering)
$a = ['a' => 1, 'b' => 2];
$b = ['b' => 20, 'c' => 3];
$leftWins = $a + $b;                     // ['a'=>1, 'b'=>2, 'c'=>3]

// 3) Overwrite by key without renumbering
$rightWins = array_replace($a, $b);      // ['a'=>1, 'b'=>20, 'c'=>3]

// 4) Deep merge (overwrite nested values)
$x = ['cfg' => ['debug' => false, 'log' => 'file']];
$y = ['cfg' => ['debug' => true,  'level' => 'info']];
$deep = array_replace_recursive($x, $y); // ['cfg'=>['debug'=>true,'log'=>'file','level'=>'info']]

// 5) Multiple arrays
$all = array_merge(...[$a, $b, ['d' => 4]]);

PHP Array Length

The next example does a PHP array length check to decide whether a merge is even needed:

<?php
if (empty($a)) {
  $out = $b;
} elseif (empty($b)) {
  $out = $a;
} else {
  $out = array_merge($a, $b);
}

$len = count($out); // length after combining

PHP Array Append

This shows PHP array append as an alternative when you are building one array incrementally.

<?php
$acc = [];
$acc[] = 'first';
array_push($acc, 'second'); // same idea; [] is usually faster/cleaner

PHP Combine Arrays

Here’s how you can use PHP to combine arrays when you want keys from one list and values from another.

<?php
$keys = ['id', 'name', 'email'];
$vals = [123, 'Ada', 'ada@example.com'];
$combined = array_combine($keys, $vals);
// ['id'=>123, 'name'=>'Ada', 'email'=>'ada@example.com']

PHP: How to Add to an Array

Sometimes you do not need to merge two full arrays. Instead, you can just add new items one by one. This shows php: how to add to an array with both shorthand and built-in functions.

<?php
$list = ['apple', 'banana'];

// Add with [] shorthand
$list[] = 'cherry';

// Or with array_push
array_push($list, 'date', 'elderberry');

// Result: ['apple', 'banana', 'cherry', 'date', 'elderberry']

This is cleaner and faster if you are just appending values rather than merging whole arrays.


Things To Consider

  • Order matters. In array_merge($a, $b), later arrays overwrite string keys and append values.
  • Numeric keys get renumbered by array_merge(). Use array_replace() or + to avoid this.
  • For nested data (array merge multidimensional PHP), array_replace_recursive() overwrites; array_merge_recursive() nests duplicates into arrays.
  • array_merge_recursive does not “overwrite.” It groups values under the same key into arrays.
  • “Deep merge” needs a clear policy. If neither built-in fits, write a custom recursive merge with overwrite rules.
  • Conditional merges are common. Filter first to avoid nulls or empty arrays (array_filter) before merging.
  • Merging more than two arrays is fine: array_merge($a, $b, $c) or array_merge(...$list).
  • PHP versions: argument unpacking (...$list) in function calls is widely available; ensure your runtime supports it.

Gotchas

Here are some of the most common pitfalls people hit when first learning how PHP handles array merging.

  • array_merge() renumbers numeric keys; this breaks positional meaning.
<?php
$a = [5 => 'apple', 10 => 'banana'];
$b = [20 => 'cherry'];

$result = array_merge($a, $b);
// Keys are renumbered: [0=>'apple', 1=>'banana', 2=>'cherry']

$union = $a + $b;
// Keys preserved: [5=>'apple', 10=>'banana', 20=>'cherry']

Renumbering means if your numeric keys matter (e.g. representing IDs, positions, or page numbers), you can’t rely on array_merge().


  • array_merge_recursive() creates arrays-of-arrays instead of overwriting; verify data integrity in PHP when combining lists.
<?php
$a = ['color' => 'red', 'size' => 'M'];
$b = ['color' => 'blue', 'style' => 'casual'];

$merged = array_merge_recursive($a, $b);
// ['color'=>['red','blue'], 'size'=>'M', 'style'=>'casual']

$replaced = array_replace_recursive($a, $b);
// ['color'=>'blue', 'size'=>'M', 'style'=>'casual']

Use it when you want to collect all values under the same key. If you only want the later value to overwrite, use array_replace_recursive() instead.

  • + keeps left keys only; right-side duplicates are ignored.
  • For PHP array merge with keys, use array_replace() if you need right-side overwrite without renumbering.
  • PHP array_merge performance degrades if called repeatedly in a tight loop; append to one array and merge once.
  • PHP merge two arrays with same keys behaves differently across methods: decide who “wins” (left via +, right via array_replace, grouped via array_merge_recursive).

Sources


Further Investigation

  • Write a custom recursive merge with strict overwrite rules and type checks.

  • Benchmark merges on large datasets; compare [] appends vs array_merge() in your workload.

  • Explore immutability patterns if frequent merges cause copies.

  • PHP Manual: Arrays


TL;DR

  • Need a quick rule: use array_merge() for appending, array_replace() to overwrite by key, + to preserve left keys, and array_replace_recursive() for nested structures.
<?php
// Quick picks
$append      = array_merge($a, $b);
$preserve    = $a + $b;
$overwrite   = array_replace($a, $b);
$deepOverwrite = array_replace_recursive($a, $b);