Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_merge that ignores key values that are not in the first/base array

Tags:

arrays

php

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);

?>
like image 700
cmorrissey Avatar asked Mar 18 '23 03:03

cmorrissey


2 Answers

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.

like image 169
axiac Avatar answered Mar 20 '23 05:03

axiac


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.

like image 34
Jonathan Kuhn Avatar answered Mar 20 '23 05:03

Jonathan Kuhn