KBD

Keith Devens .com

Monday, December 1, 2008 Flag waving
Communicating badly and then acting smug when misunderstood is not cleverness. – Randall Munroe (xkcd)
← 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

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)
:

December 2008
SunMonTueWedThuFriSat
 123456
78910111213
14151617181920
21222324252627
28293031 



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

Recent comments XML

new⇒Free image hosting sites

Well, TinyPic has this in its​FAQ:

> Images and videos is in​your accoun...

Keith: Dec 1, 1:13am

Join a NameValueCollection into a querystring in C#

Well with a lamba expression, this​is what I came up​with:

?!code:csharp...

Gustaf Lindqvist: Nov 30, 4:38pm

Why no generic OrderedDictionary?

Check​http://www.codeproject.com/KB/recip​es/GenericOrderedDictionary.aspx?d...

Gabrielk: Nov 27, 6:57am

WhatIsMyIP.com

http://www.thesysteminfo.com is​another good alternate to​whatismp.com... I...

Kripz: Nov 26, 8:51pm

Girls, please don't get breast implants

Actually I think it's sweet when a​man loves a woman whether she's big​or n...

218.186.12.228: Nov 26, 9:40am

Generated in about 0.186s.

(Used 8 db queries)

mobile phone