Solved

array_merge renumbered my keys and I lost the IDs

Asked by Priya Nair · 417 views · 2 replies

Priya Nair8 messages · 3 solutions

I am merging two maps keyed by user ID:

$a = [14 => 'Priya', 22 => 'Tomasz'];
$b = [31 => 'Hannah'];

print_r(array_merge($a, $b));
// [0 => 'Priya', 1 => 'Tomasz', 2 => 'Hannah']

The IDs are gone. Is there a flag for this or am I using the wrong function?

2 replies

Rafael MendesSolution

Wrong function for this job — array_merge renumbers integer keys by design, because its main use is appending lists. String keys are preserved; integer keys are not.

Two alternatives depending on which side should win a collision:

// Left wins: existing keys are kept, new ones added.
$result = $a + $b;

// Right wins: later values overwrite earlier ones.
$result = array_replace($a, $b);

Both keep the integer keys. The + operator surprises people the other way round, so it is worth saying plainly: $a + $b does not let $b overwrite $a. If you want the right-hand side to win, you want array_replace.

Link
Priya Nair

array_replace was what I wanted. I had assumed + worked like a merge with overwrite, which explains a bug I fixed by accident last week.

Link