0

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

)
chchrist
  • 18,854
  • 11
  • 48
  • 82
  • what u expect to get in result – Haim Evgi Sep 08 '11 at 08:01
  • 1
    Do you want the *keys only* or the *values* for the keys (in which case I assume the value for a given key is going to be the same in both arrays)? – Jon Sep 08 '11 at 08:02
  • the arrays merged with unique keys values. For example I don't want the [16] => 16 to appear two times – chchrist Sep 08 '11 at 08:03
  • 1
    This doesnt clarify it for me. Please give a full example output. Also see [+ operator for arrays](http://stackoverflow.com/questions/2140090/operator-for-array-in-php) – Gordon Sep 08 '11 at 08:04
  • 1
    Also: give the *smallest* example that explains what you need. There's no need to put 15 elements in each array to illustrate. – Jon Sep 08 '11 at 08:07
  • 1
    please use var_export, not print_r, when dumping arrays :) – Arnaud Le Blanc Sep 08 '11 at 08:07
  • eh, wait. now you also want it sorted and reindexed? – Gordon Sep 08 '11 at 08:13

4 Answers4

4
$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().

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
3
$merged = array_unique(array_merge($array1, $array2));
Alfwed
  • 3,307
  • 2
  • 18
  • 20
1

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);
Kees Schepers
  • 2,248
  • 1
  • 20
  • 31
0

Try this:

$merged = array_unique(array_merge($array1, $array2));
Gordon
  • 312,688
  • 75
  • 539
  • 559
Niko
  • 26,516
  • 9
  • 93
  • 110