0

I have the below snippet of code and I can't figure out why these two arrays won't merge - likely due to not understanding 100% how array_merge works. I'm expecting to see the duplicate, and merge the two into a single key. Running array_unique results in errors. Any ideas, or possibly an alternate solution to merge these two?

$a['12345']['label']    = '12345';
$a['12345']['type']     = 'Newspaper';

$b['12345']['label']    = '12345';
$b['12345']['type']     = 'Newspaper';

$result = array_merge($a, $b);

echo "<pre>";
print_r($result);
Bobby Bruce
  • 341
  • 5
  • 12
  • Array merge can't do duplicates. You have the same keys, so one set of data must overwrite another. – Styphon May 06 '16 at 15:10

2 Answers2

2

From the docs

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

The short answer is that the merge is occurring, just not in the way you desire.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 1
    Explanation of array_merge and possible solution: http://stackoverflow.com/questions/5929642/php-array-merge-with-numerical-keys – jbrya029 May 06 '16 at 15:13
  • Perfect, this resolves it. Also @jbrya029 thanks for that link, that `+` operator successfully merged them – Bobby Bruce May 06 '16 at 15:29
0

Because they would have the same keys. Try changing $b['12345'] to $b['12346'] and see if they merge.

Mike J
  • 425
  • 4
  • 15