KBD

Keith Devens .com

Thursday, March 18, 2010 Flag waving
Je n'ai fait celle-ci plus longue que parce que je n'ai pas eu le loisir de la... – Blaise Pascal (Lettres Provinciales)
← SharpReader is awesomeOne more argument against the latest cry of "It's all about oil!" →

Daily link icon Friday, April 18, 2003

Updated PHP function to merge two arrays

I was just reminded to post my final version of the function I wrote to merge two arrays in the way I needed it.

<?php
function merge(&$a, &$b){
    if(
is_array($a) and is_array($b)){
        if(isset(
$a[0])){ # $a is a numeric array, so copy b straight over it
            
$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];
            }
        }
    }else{
        
$a $b;
    }
}
?>

This merges two arrays key for key, recursively, unless array $a is a plain old numeric array rather than an associative array, in which case it overwrites array $a with array $b. If a key exists in both arrays (and the value is a scalar, instead of another array, in which case it would recurse), it overwrites the value in array $a with the value from array $b. If $a and $b aren't both arrays, then $a is overwritten by $b.

← SharpReader is awesomeOne more argument against the latest cry of "It's all about oil!" →

Comments XML gif


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

March 2010
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 2 posts

Recent comments XML

new⇒I hate ASP.NET

I hate ASP... I was doing wonders​with PHP, then suddenly one of my​clients...

Johnies: Mar 17, 6:14am

Quantum physics and free will

I knew you were going to say that....

Tom Massey: Mar 15, 9:26pm

Generated in about 0.101s.

(Used 8 db queries)