Archive for February, 2010

Deep merging two arrays in PHP

Thursday, February 4th, 2010

PHP has a wealth of functions for manipulating arrays, however; I often want to deep merge 2 arrays whilst maintaining the key => value structure. PHP does have functions that will merge multiple arrays but they attempt to maintain duplicate keys.

The below function take 2 arguments (arrays). Arguments are in order of importance, the second arguments values will always overwrite the first arguments values and so on.

function array_merge_replace($base_array, $merge_array){
	$new_array = array();
	$key_list = array_merge((array)$base_array, (array)$merge_array);
	foreach($key_list as $k=>$v){
		if(is_array($base_array[$k])||is_array($merge_array[$k])){
			$new_array[$k] = array_merge_replace($base_array[$k], $merge_array[$k]);
		}else{
			$new_array[$k] = $merge_array[$k] ? $merge_array[$k] : $base_array[$k];
		}
	}
	return $new_array;
}

© 2006 - 2010 Matt Lowden. Creative Commons all rights reserved.