PHP's array_merge function is a perfect way of combining arrays. However, it doesn't properly merge keys (and values) from arrays outside of the first instance. Let's create our own function and fix this issue.

The Issue with the Default array_merge PHP function

As seen in the example of array_merge below, the issue is how the default function doesn't merge values if any subsequent array's field is empty; it doesn't merge, it erases. In this instance, we are combining CD Albums to create a playlist, and the problem becomes clear.

The first (band) array $dashboard has had two albums which were top hits, while the second (band) array $brand_new has not. When we use array_merge, instead of merge actual (albums) values, it only takes the last instance of the field and thus messing up our playlist!

Creating a Custom array_merge PHP Function

/* Array Merge Retain

------------------------------------------------------*/

function array_merge_retain($array_a=array(),$array_b=array()){

$array_merge= array();

if(!empty($array_a)&& !empty($array_b)){

foreach($array_a as $field=>$value){

$array_merge[$field]= $value;

}

foreach($array_b as $field=>$value){

if(!empty($value)){

$array_merge[$field]= $value;

} elseif(!array_key_exists($field,$array_a)){

$array_merge[$field]= $value;

}

}

}

return $array_merge

}

The premise is that we iterate over the first array and create the merged array based on its fields and values. We then iterate over the second array, if any field does not exist within the merged array it is added, if any field does exists and it is not empty, only then is it merged.