Create a Smart array_merge Function

Create a Smart array_merge Function

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!

The Problem with the PHP function array_merge

Creating a Custom array_merge PHP Function

  1. /* Array Merge Retain
  2. ------------------------------------------------------*/
  3. function array_merge_retain($array_a=array(),$array_b=array()){
  4.  
  5. $array_merge= array();
  6.  
  7.  
  8. if(!empty($array_a)&& !empty($array_b)){
  9.  
  10. foreach($array_a as $field=>$value){
  11.  
  12. $array_merge[$field]= $value;
  13.  
  14. }
  15.  
  16.  
  17. foreach($array_b as $field=>$value){
  18.  
  19. if(!empty($value)){
  20.  
  21. $array_merge[$field]= $value;
  22.  
  23. } elseif(!array_key_exists($field,$array_a)){
  24.  
  25. $array_merge[$field]= $value;
  26.  
  27. }
  28.  
  29. }
  30.  
  31. }
  32.  
  33.  
  34. return $array_merge
  35.  
  36. }

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.

The Results

By applying our new array_merge_retain function, the empty (top hits) values are ignored, actual ones are retained, and our playlist is complete & intact!

The Results of the Solution to the PHP function array_merge Problem

Tags

Add Comment

Leave a Comment or Reply
Fuel the conversation with your thoughts using the form below. Email is not made public.
× Processing...

Please Wait while your Comment is being Processed.

*
*
*

Comments 0 Total Responses