Just like jQuery's extend, this code will allow you to replace existing values of an array with new values, based solely on matching keys.

Usage

The following code would place all values in $b into those of $a, if they have the same key, then print it out. Next, it does the opposite procedure and prints that as well.

$a = array("lemon" => "sour","candy" => "sweet","potatoes" => "starchy");
$b = array("candy" => "ick");
print_r(array_extend($a,$b));
print_r(array_extend($b,$a));

The result is:

Array
(
    [lemon] => sour
    [candy] => ick
    [potatoes] => starchy
)
Array
(
    [candy] => sweet
)

Code

function array_extend($array) { 
    if (!is_array($array))
        return $array;
    $args = func_get_args();
    if (count($args) > 2) {
        foreach ($args as $arg)
            if (is_array($arg))
                $array = array_extend($array,$arg);
    } else if (count($args) == 2) {
        if (!is_array($args[1]))
            return $array;
        foreach ($array as $key => $val)
            if (array_key_exists($key,$args[1]))
                $array[$key] = $args[1][$key];
    }
    return $array;
}

Next Post Previous Post