Reputation: 943
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
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
Reputation: 2974
You should use array_merge:
array_merge($array1, $array2);
Upvotes: 0
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