My name is  
Jurgens du Toit.
Systems Developer.
Problem Solver.

About Me

Technology and Solving Problems are my passion. I'm a South African that loves my wife, life, and coding.

I'm writing a book!

The Logstash Config Guide

Buy it now on Leanpub

08 January 2013

PHP's array_merge_recursive function explained

By Jurgens du Toit

Reading the PHP docs, it’s not immediately clear how the array_merge_recursive function behaves. I’ve setup a couple of test cases and compared them with the plain array_merge function to explain it further:

The following snippet set’s up a couple of arrays, and outputs them for completeness sake.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$cats = array(
    'white' => array('Kitty'),
    'brown' => 'Bach',
    'mixed' => array('Tomcat')
);
$dogs = array(
    'white' => 'Bowser',
    'brown' => 'Rex',
    'mixed' => ('Mutt')
);

var_dump('Cats', $cats, 'Dogs', $dogs);
?>
string 'Cats' (length=4)
array
  'white' => 
    array
      0 => string 'Kitty' (length=5)
  'brown' => string 'Bach' (length=4)
  'mixed' => 
    array
      0 => string 'Tomcat' (length=6)
string 'Dogs' (length=4)
array
  'white' => string 'Bowser' (length=6)
  'brown' => string 'Rex' (length=3)
  'mixed' => string 'Mutt' (length=4)

This snippet highlights what happens when the arrays being merged have matching keys.

1
2
3
4
<?php
var_dump('Cats and Dogs - plain', array_merge($cats, $dogs));
var_dump('Cats and Dogs - recursive', array_merge_recursive($cats, $dogs));
?>

All values that’s not already in an array will be placed in an array, and merged with other values with the same keys. Arrays are left as they are and then merged.

array
  'white' => 
    array
      0 => string 'Kitty' (length=5)
      1 => string 'Bowser' (length=6)
  'brown' => 
    array
      0 => string 'Bach' (length=4)
      1 => string 'Rex' (length=3)
  'mixed' => 
    array
      0 => string 'Tomcat' (length=6)
      1 => string 'Mutt' (length=4)

Compare this with the normal array_merge function, where the values of the latter arrays replace all the values with the same key.

array
  'white' => string 'Bowser' (length=6)
  'brown' => string 'Rex' (length=3)
  'mixed' => string 'Mutt' (length=4)

Values with numerical keys get added to the original array with a renumbering of keys. This is the same behaviour as that of array_merge.

blog comments powered by Disqus