Skip to content

Instantly share code, notes, and snippets.

@chadhutchins
Created August 31, 2010 01:44
Show Gist options
  • Save chadhutchins/558385 to your computer and use it in GitHub Desktop.
Save chadhutchins/558385 to your computer and use it in GitHub Desktop.
<?php
// custom array merging
// if something exists in the custom array, it should overwrite the default
// otherwise take the default value
$default = array(
"key1" => "val1",
"key2" => "val2",
"key3" => array(
"1" => "one",
"2" => "two"
),
"key4" => "four"
);
$custom = array(
"key1" => "val1",
"key2" => "newval",
"key3" => array(
"1" => "one",
"2" => "too"
),
);
$result = merge($default,$custom);
function merge($a, $b) {
$temp = array();
foreach ($a as $key => $val) {
if (array_key_exists($key, $b)) {
if (is_array($val))
$temp[$key] = merge($a[$key],$b[$key]);
else
$temp[$key] = $b[$key];
} else
$temp[$key] = $val;
}
return $temp;
}
/*
$result = array(
"key1" => "val1",
"key2" => "newval",
"key3" => array(
"1" => "one",
"2" => "too"
),
"key4" => "four"
);
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment