11

I like to learn how to combine two associative array which has same keys but different values like how we do in jQuery with var options = $.extend(defaults, options);

$first = array("name"=>"John","last_name"=>"McDonald","City"=>"World"); //default values
$second = array("name"=>"Michael","last_name"=>"Jackson"); //user provided

$result = combine($first,$second);

//output array("name"=>"Michael","last_name"=>"Jackson","City"=>"World");

I am looking for something built-in instead of writing a entire new function to provide this feature. Of course if you have something neat, just let me know.

Thanks...

7 Answers 7

35
$result = array_merge($first, $second);

As long as you're dealing with string keys, array_merge does exactly what you want. The two arrays are combined, and where the two have the same keys, the values from $second overwrite the values from $first.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes it's good with one small drawback. Array_merge will reorder numeric keys! So, if you have numeric keys in your array (for example numeric constant values), then you can't use array_merge correctly.
5

array_merge()

Comments

3

I think array_merge() or array_combine() are the functions you are searching for.

2 Comments

+1 for array_combine(). PHP has a lot of great built-in functions I fall in love with.
Why +1 for array_combine()? array_combine() is not going to do anything here if you have the array described by OP. array_combine() combines an array of keys with an array of values.
1

if you know exactly which key you want override you can simply do that like this $first['name']="jastin"; otherwise you have to use array_merge

Comments

0

you can iterate on second array and setting each element in first array

Comments

0

I think array_merge() or array_combine() are the functions you are looking for array_merge() may used to merge the two array which are further called. and the array_combine() the keys of a array with the values of a another array.

Comments

0

I've never found a built-in function for this (simple) need, so I developed a custom function in order to override a $default array with an $override array:

function array_override( $default, $override )
{
    foreach( $default as $k=>$v )
    {
        if( isset( $override[$k] ) ) $default[$k] = $override[$k];
    }
    return $default;
}

As you can see, values in $default are overridden only if are set on the $override array; otherwise the $default value remain on the returned array.

Comments

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.