Background: Trevor is working with a PHP implementation of a standard algorithm: take a main set of default name-value pairs, and update those name-value pa
array_replace_recursive($array, $array2);
This is the solution.
Well, if you want a "clever" way to do it, here it is, but it may not be as readable as simply doing a loop.
$merged = array_merge(array_filter($foo, 'strval'), array_filter($bar, 'strval'));
edit: or using +...
Try this:
$merged = array_map(
create_function('$foo,$bar','return ($bar?$bar:$foo);'),
$foobar,$feebar
);
Not the most readable solution, but it should replace only non-empty values, regardless of which order the arrays are passed..
This will put duplicates into a new array, I don't know if this is what you want though.
<?php
$foobar = Array('firstname' => 'peter','age' => '33',);
$feebar = Array('firstname' => '','lastname' => 'griffin',);
$merged=$foobar;
foreach($feebar as $k=>$v){
if(isset($foobar[$k]))$merged[$k]=array($v,$foobar[$k]);
else $merged[$k]=$v;
}
print_r($merged);
?>
This will simply assure that feebar will never blank out a value in foobar:
<?php
$foobar = Array('firstname' => 'peter','age' => '33',);
$feebar = Array('firstname' => '','lastname' => 'griffin',);
$merged=$foobar;
foreach($feebar as $k=>$v) if($v)$merged[$k]=$v;
print_r($merged);
?>
or ofcourse,
<?
function cool_merge($array1,$array2){
$result=$array1;
foreach($array2 as $k=>$v) if($v)$result[$k]=$v;
return $result;
}
$foobar = Array('firstname' => 'peter','age' => '33',);
$feebar = Array('firstname' => '','lastname' => 'griffin',);
print_r(cool_merge($foobar,$feebar));
?>
If you also want to keep the values that are blank in both arrays:
array_filter($foo) + array_filter($bar) + $foo + $bar
Adjust to your needs:
# Replace keys in $foo
foreach ($foo as $key => $value) {
if ($value != '' || !isset($bar[$key])) continue;
$foo[$key] = $bar[$key];
}
# Add other keys in $bar
# Will not overwrite existing keys in $foo
$foo += $bar;