← back to archive

January 8, 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.

  <?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.

  <?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.

← more posts