0

I have two arrays like this

$array1 = ['name'=>'john', 'age'=> 10]
$array2 = ['name' => 'johnKaff', 'class' => 'User', 'option'=array('c1', 'c2')]

The result i want is

$array2 = ['name' => 'john', 'class' => 'User', 'option'=array('c1', 'c2'), 'age'=> 10]

The values from $array1 should always override if have same key in $array2

1
  • 1
    Have you tried array_merge? Commented Feb 19, 2014 at 20:20

3 Answers 3

1

Use array_replace():

$result = array_replace($array2, $array1);

Where:

  • $array1 - The array in which elements are replaced.
  • $array2 - The array from which elements will be extracted.

Output:

Array
(
    [name] => john
    [class] => User
    [option] => Array
        (
            [0] => c1
            [1] => c2
        )

    [age] => 10
)
Sign up to request clarification or add additional context in comments.

3 Comments

whats the diff between this and array_merge
array_replace() replaces the values of the first array with the same values from all the following arrays. array_merge() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one and returns the resulting array.
@user3147180: Basically, array_replace() does a replace whereas array_merge() merges second array at the end of the first.
1

Use the + operator:

$combined_array = $array1 + $array2;

The array listed first wins when each array has an element with the same key.

Example:

$array1 = array('name'=>'john', 'age'=> 10);
$array2 = array('name' => 'johnKaff', 'class' => 'User', 'option'=>array('c1', 'c2'));
$combined_array = $array1 + $array2;
var_dump($combined_array);

Output:

array(4) {
    ["name"]=>
      string(4) "john"
    ["age"]=>
      int(10)
    ["class"]=>
      string(4) "User"
    ["option"]=>
      array(2) {
        [0]=>
          string(2) "c1"
        [1]=>
          string(2) "c2"
      }
}

Comments

0

You should use array_merge:

array_merge($array1, $array2);

1 Comment

same keys in second associative array will overwrite previous. Use arguments in reverse order: array_merge($array2, $array1);

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.