user3147180
user3147180

Reputation: 943

How to merge array by taking values from other array in php

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

Upvotes: 0

Views: 42

Answers (3)

elixenide
elixenide

Reputation: 44823

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"
      }
}

Upvotes: 1

You should use array_merge:

array_merge($array1, $array2);

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76646

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
)

Upvotes: 1

Related Questions