Skip to content

Instantly share code, notes, and snippets.

@ryaan-anthony
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save ryaan-anthony/3dacdf3a722217eb66f0 to your computer and use it in GitHub Desktop.

Select an option

Save ryaan-anthony/3dacdf3a722217eb66f0 to your computer and use it in GitHub Desktop.
<?php
// source arrays
$source_1 = [
'abc' => [0 => 'a'],
'b' => 'c'
];
$source_2 = [
'abc' => [1 => 'b', 2 => 'c'],
'b' => 'b'
];
// test 1 - array_merge
$result_1 = array_merge($source_1, $source_2);
var_dump($result_1);
// test 2 - array_merge_recursive
$result_2 = array_merge_recursive($source_1, $source_2);
var_dump($result_2);
// test 3 - recursive_merge
function recursive_merge($arr1, $arr2)
{
if(!is_array($arr1) || !is_array($arr2)) return $arr2;
foreach($arr2 as $key => $val2){
$val1 = isset($arr1[$key]) ? $arr1[$key] : [];
$arr1[$key] = recursive_merge($val1, $val2);
}
return $arr1;
}
$result_3 = recursive_merge($source_1, $source_2);
var_dump($result_3);
// Test 1 array_merge (undesirable: missing the 'a' value)
//
// array (size=2)
// 'abc' =>
// array (size=2)
// 1 => string 'b' (length=1)
// 2 => string 'c' (length=1)
// 'b' => string 'b' (length=1)
//
// Test 2 array_merge_recursive (undesirable: 'b' index is now an array)
//
// array (size=2)
// 'abc' =>
// array (size=3)
// 0 => string 'a' (length=1)
// 1 => string 'b' (length=1)
// 2 => string 'c' (length=1)
// 'b' =>
// array (size=2)
// 0 => string 'c' (length=1)
// 1 => string 'b' (length=1)
//
// Test 3 recursive_merge (desired result)
//
// array (size=2)
// 'abc' =>
// array (size=3)
// 0 => string 'a' (length=1)
// 1 => string 'b' (length=1)
// 2 => string 'c' (length=1)
// 'b' => string 'b' (length=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment