If you plan to only have primitive values in the keys (strings, numbers etc.) this will work:
<?php
function array_combine_keys($a, $b) {
$c = $a;
foreach ($b as $k=>$v) {
// Value can be only primitive, not an array itself
if (isset($a[$k]) && $a[$k] !== $v) {
$c[$k] = array($a[$k], $v);
} else {
$c[$k] = $v;
}
}
return $c;
}
$a = array('a' => '1', 'b' => '2');
$b = array('a' => '1', 'b' => '3', 'c' => '5');
var_dump(array_combine_keys($a, $b));
?>
array(3) {
["a"]=>
string(1) "1"
["b"]=>
array(2) {
[0]=>
string(1) "2"
[1]=>
string(1) "3"
}
["c"]=>
string(1) "5"
}
A more versatile way is to allow arrays in the values as well, and to ensure the keys are always arrays irrespectively - this means we won't need extra logic to check if the key is an array or isn't an array when traversing the result. The (+) is the union of the two arrays.
<?php
function array_combine_keys($a, $b) {
$c = $a;
foreach ($b as $k=>$v) {
if (!is_array($v)) {
$v = array($v);
}
if (isset($a[$k])) {
$av = $a[$k];
if (!is_array($av)) {
$av = array($av);
}
$c[$k] = $av + $v;
} else {
$c[$k] = $v;
}
}
return $c;
}
$a = array('a' => '1', 'b' => array('2', '4'));
$b = array('a' => '1', 'b' => array('3'), 'c' => '5');
var_dump(array_combine_keys($a, $b));
?>
array(3) {
["a"]=>
array(1) {
[0]=>
string(1) "1"
}
["b"]=>
array(2) {
[0]=>
string(1) "2"
[1]=>
string(1) "4"
}
["c"]=>
array(1) {
[0]=>
string(1) "5"
}
}