I was wondering if there was a function that would merge two or more arrays but would ignore any key value which is not contained with in the first/base array.
Here is a quick example of what I am doing with the current result and the result I am looking for.
<?php
$array1 = array('a' => 1, 'b' => 2);
$array2 = array('b' => 3, 'c' => 4);
$result = array_merge($array1, $array2);
// current result
// $result = array('a' => 1,'b' => 3, 'c' => 4);
// what i would like
// $result = array('a' => 1,'b' => 3);
?>
The request "ignore any key value which is not contained with in the first/base array" calls for array_intersect_key()
$array1 = array('a' => 1, 'b' => 2);
$array2 = array('b' => 3, 'c' => 4);
$result = array_merge($array1, array_intersect_key($array2, $array1));
array_intersect_key($array2, $array1)
compares the keys of $array2
and $array1
and keeps the values from $array2
that are associated with the keys that are common to both arrays.
Here is a quick example that I just wrote:
function array_merge_custom(){
//get all the arguments
$arrays = func_get_args();
//get the first argument
$first = array_shift($arrays);
//loop over the first argument by key and value
foreach($first as $key=>&$value){
//loop over remaining arrays
foreach($arrays as $otherArray){
//check if key from first array exists in subsequent array
if(array_key_exists($key, $otherArray)){
//overwrite value
$value = $otherArray[$key];
}
}
}
//return the first array with new values
return $first;
}
http://codepad.viper-7.com/AE9rkV
Benefit of this is that it works for any number of arrays, not just 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With