Skip to content
Advertisement

PHP’s array_merge_recursive behaviour on integer keys

Is there an approach for recursively merging arrays, in the same way as PHP’s array_merge_recursive() function does, except that integer keys are treated the same as string keys?

(It’s important for the process that the keys remain parse-able as integers.)

For example:

$a = array(
    'a' => array(1)
);
$b = array(
    'a' => array(2, 3)
);
var_dump(array_merge_recursive($a, $b));

Will merge the on the "a" key and output, as expected, the following:

array(1) {
    ["a"] => array(3) {
        [0] => int(1)
        [1] => int(2)
        [2] => int(3)
    }
}

However, when using integers for keys (even when as a string):

$a = array(
    '123' => array(1)
);
$b = array(
    '123' => array(2, 3)
);
var_dump(array_merge_recursive($a, $b));

array_merge_recursive() will return:

array(2) {
    [0] => array(3) {
        [0] => int(1)
    }
    [1] => array(2) {
        [0] => int(2)
        [1] => int(3)
    }
}

Instead of the much desired:

array(1) {
    ["123"] => array(3) {
        [0] => int(1)
        [1] => int(2)
        [2] => int(3)
    }
}

Thoughts?

Advertisement

Answer

you can prefix the array keys with a short string:

function addPrefix($a) {
    return '_' . $a;
}
# transform keys
$array1 = array_combine(array_map('addPrefix', array_keys($array1)), $array1);
$array2 = array_combine(array_map('addPrefix', array_keys($array2)), $array2);
# call array_combine
$array = array_merge_recursive($array1, $array2);
# reverse previous operation  
function stripPrefix($a) {
     return substr($a, 1);
}
$array = array_combine(array_map('stripPrefix', array_keys($array)), $array)     
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement