KBD

Keith Devens .com

Thursday, May 17, 2012 Flag waving
Battle not with monsters lest ye become a monster and if you gaze into the abyss the abyss gazes into... – Friedrich Nietzsche
← Pro-life position growing among youthApplication configuration using ZConfig →

Daily link icon Sunday, March 30, 2003

PHP function to merge two arrays

Hey, I just impressed myself a little. I thought this code was going to take a little longer than it did, but I got it essentially on the first try, and quickly.

<?php
function merge(&$a, &$b){
    
$keys array_keys($a);
    foreach(
$keys as $key){
        if(isset(
$b[$key])){
            if(
is_array($a[$key]) and is_array($b[$key])){
                
merge($a[$key],$b[$key]);
            }else{
                
$a[$key] = $b[$key];
            }
        }
    }
    
$keys array_keys($b);
    foreach(
$keys as $key){
        if(!isset(
$a[$key])){
            
$a[$key] = $b[$key];
        }
    }
}
?>

I actually got it on the second try, but only because I forgot that second part that copies the values for the keys that didn't exist in the first array from the second (duh).

Anyway, I figured it was neat, so I blogged it. Smiley I was going to go into a longer post about why none of array_merge, array_merge_recursive, and the normal array '+' operator that I didn't even know about did what I wanted, but I still have to study for my probability and statistics exam tomorrow.

Update: I knew I should have waited to post this. There's a bug if the two arrays don't have the same structure. In other words, if one has an array for a given key where the other has a scalar, it won't work. But I think it's only if the first array has a scalar and the second one has an array, and not the other way around. I'll post a corrected version here when I get it right Smiley

Update: Ok, fixed. Neglected to check that both $a[$key] and $b[$key] were arrays. So now it works exactly like I expected it to. However, because of how my CMS works, the way I planned it isn't actually the way I need it to work Smiley So I'll have to deal with that later...

Update: Over in the HiveMinds forum there's a discussion of this code:

Now, I took a couple passes over the code, and it looks like to me that if a value for the same key exists in both arrays, the value from array b will overwrite the value in array a. What am I missing here? How is this truly a merge? I see how the second block adds to a things that don't exist in b, but the first code block (other than the section that calls merge recursively if both keys are really arrays) seems to overwrite the slot in a with the value in b. Maybe thats just what he wants it to do. Am I missing something here? I'm sure its right in front of me and I'm just not seeing it.

That's what I intended. I mentioned above that I didn't have time to explain why PHP's built in array_merge and array_merge_recursive functions, and the built-in array '+' operator weren't what I needed. But what the poster describes is exactly what I intended. Notice, however, that this code does in fact behave similarly to the array_merge function and the built-in array '+' operator (except maybe for numeric indices -- I have to make sure), except that those aren't recursive.

The reason I needed this type of merge function is because, in my CMS, "more specific" settings overwrite "less specific" settings as I parse through the configuration file. Unfortunately, this code doesn't do what my CMS needs when the arrays have numeric indices.

Update: check out the new version.

← Pro-life position growing among youthApplication configuration using ZConfig →

Comments XML gif

jmikec (http://www.hiveminds.info/) wrote:

Thanks for the explanation and the link to Hiveminds.

We are the core group of developers and designers that were part of C|Net's Builder Buzz community (was part of Builder.com). When they decided to toss away their community, we started our own thing. Things are still rough around the edges, because most of us are employed full time and only get to work on building our site when we have a few spare minutes, but we welcome new members. Hope to see you around there from time to time!

∴ jmikec | 1-Apr-2003 10:57am est | http://www.hiveminds.info/ | #1727

Chris wrote:

Why not just:

function merge_assoc($arr1, $arr2){
   foreach($arr2 as $k => $v){
      if(isset($arr1[$k])){
         $arr1[$k] = $v;
      }else{
         $arr1[] = $v;
      }//if-else
   }//foreach
   
   return $arr1;
}
∴ Chris | 14-Oct-2009 8:46am est | #11424

Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

May 2012
SunMonTueWedThuFriSat
 12345
6789101112
13141516171819
20212223242526
2728293031 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 4 posts

Recent comments XML

new⇒Acknowledging the Arrival of Peak Government

In many ways, Peak Oil is​responsible for this new​uselessness of the big g...

Revence: May 16, 6:35am

new⇒Tab EXSPLOSION

Right now, I, too, have too many​tabs open. A rough count says​25.
Right. ...

Revence: May 16, 6:21am

George W. Bush: ‘I’m for Mitt Romney’ - ABC News

A marked difference (departure,​even) from the KBD of eight--yea,​even four...

Revence: May 15, 1:55pm

WebOb — WSGI request and response objects

Google App Engine forces one to​learn these....

Revence: May 15, 1:52pm

Generated in about 0.221s.

(Used 8 db queries)