I would like to set an associative array of default keys and values(array1); If an array is provided (array2) then all indexes from array1 will be overwritten by array2 where the keys match. Any additional keys in array2 wont be added to array1.
One solution is to run a loop and do a array_key_exists like so.
$new_array = $array1;
foreach ($array2 as $key => $value) {
if(array_key_exists($key, $array1)){
$new_array[$key] = $value; //overwrite default value
} else {
// new key, dont add
}
}
but is there a php function which does this already ?
the functions i have tries already dont give my the results i would like.
$array1 = array(
'one' =>'one',
'two' => 'two',
'three' => 'three',
'four' => 'four'
);
$array2 = array(
'two' => '2',
'four' => '4',
'six' => '6',
);
var_dump($array1+$array2);
array (size=5)
'one' => string 'one' (length=3)
'two' => string 'two' (length=3)
'three' => string 'three' (length=5)
'four' => string 'four' (length=4)
'six' => string '6' (length=1)
var_dump(array_merge($array1,$array2));
array (size=5)
'one' => string 'one' (length=3)
'two' => string '2' (length=1)
'three' => string 'three' (length=5)
'four' => string '4' (length=1)
'six' => string '6' (length=1)
var_dump(array_replace($array1,$array2));
array (size=5)
'one' => string 'one' (length=3)
'two' => string '2' (length=1)
'three' => string 'three' (length=5)
'four' => string '4' (length=1)
'six' => string '6' (length=1)
The result i am looking for would be
array (size=4)
'one' => string 'one' (length=3)
'two' => string '2' (length=1)
'three' => string 'three' (length=5)
'four' => string '4' (length=1)