2

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

1 Answer 1

4

Take from 2nd array keys, present in 1st, and replace value in 1st

print_r(array_replace($array1, array_intersect_key($array2, $array1)));
Sign up to request clarification or add additional context in comments.

1 Comment

Two seconds before me. :) Nice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.