Ichier » coding » ichier's coding corner
{ php }  
  array_merge_rec
date 2005
update 2005
code <?php
function array_merge_rec($a1,$a2) {        //coded by Ichier2005
    
if(!is_array($a1)) { return $a2; }
    if(!
is_array($a2)) { return $a1; }
    foreach(
$a2 as $key => $val) {
        if(
is_array($val)) {
            
$a1[$key] = array_merge_rec($a1[$key],$val);
        } else {
            
$a1[$key] = $val;
        }
    }
    return 
$a1;
}
?>
description completeley merge arrays recoursive, without deleting any value of the first array wich is not present in the second
when keys are set in both arrays, the second overwrites the first.
syntax <?php
array = array_merge_rec(array array1, array array2);
?>
explanation we take 2 arrays and merge them:
<?php
    $arrayA
["personal"]["name"] = "Niko";
    
$arrayA["personal"]["age"] = 25;
    
$arrayA["contact"]["town"] = "Berlin";
    
$arrayA["contact"]["tel1"] = "030/123";
    
$arrayA["contact"]["fax"] = "030/125";

    
$arrayB["personal"]["name"] = "Nikolaos";
    
$arrayB["personal"]["gender"] = "male";
    
$arrayB["contact"]["town"] = "Berlin";
    
$arrayB["contact"]["tel1"] = "030/123";
    
$arrayB["contact"]["tel2"] = "030/124";

    
$array array_merge_rec($arrayA$arrayB);
?>

the resulting array would be:

<?php
    $array
["personal"]["name"] = "Nikolaos";
    
$array["personal"]["age"] = 25;
    
$array["personal"]["gender"] = "male";
    
$array["contact"]["town"] = "Berlin";
    
$array["contact"]["tel1"] = "030/123";
    
$array["contact"]["tel2"] = "030/124";
    
$array["contact"]["fax"] = "030/125";
?>