Reputation: 19842
I want to merge those two arrays and get only the unique key values. Is there a php function for this? array_merge() doesn't work.
Array
(
[1] => 3
[2] => 4
[3] => 1
)
Array
(
[1] => 3
[2] => 1
[3] => 2
)
RESULT ARRAY THAT I WANT
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
Upvotes: 0
Views: 242
Reputation: 2258
Following peice of code gives exact what you wants but the question is do you really want the keys in the result are starting from 1 instead of 0? If you don't Arnaud his option is the best solution.
$array1 = array(
1 => 3,
2 => 4,
3 => 1
);
$array2 = array(
1 => 3,
2 => 1,
3 => 2
);
$values = array_unique(array_merge($array1, $array2));
$keys = array_keys(array_fill_keys($values, ''));
$result = array_combine($keys, $values);
asort($result);
var_dump($result);
Upvotes: 1
Reputation: 99919
$values = array_unique(array_merge($array1, $array2));
sort($values);
This returns the unique values from array1 and array2 (as per your example).
Try it here: http://codepad.org/CeZewRNT
See array_merge()
and array_unique()
.
Upvotes: 4