2

How can I combine both of these arrays and if there is duplicates of an array have only one represented using PHP.

Array
(
    [0] => 18
    [1] => 20
    [2] => 28
    [3] => 29
)

Array
(
    [0] => 1
    [1] => 8
    [2] => 19
    [3] => 22
    [4] => 25
    [5] => 28
    [6] => 30
)
Ross
  • 18,117
  • 7
  • 44
  • 64
HELP
  • 14,237
  • 22
  • 66
  • 100
  • 1
    do you have to maintain index association? If so, how should duplicates be treated? – Gordon Oct 15 '10 at 10:20
  • if you mean index by [0], [1], no not really – HELP Oct 15 '10 at 10:22
  • 1
    *(related)* [+ operator for array in PHP?](http://stackoverflow.com/questions/2140090/operator-for-array-in-php) – Gordon Oct 15 '10 at 10:23
  • @stepit yes, sorry for that that.I changed the text to read *related* instead. SO doesnt allow me to remove the closevote though. – Gordon Oct 15 '10 at 10:36

3 Answers3

10

It sounds like you need:

 array_unique(array_merge($first_array, $second_array));
mario
  • 144,265
  • 20
  • 237
  • 291
3

Apply array_unique to the results of the array_merge function.

Example:

php > $f=array(1,2,3,4,5);
php > $r=array(4,5,6,7,8);
php > print_r(array_unique(array_merge($r,$f)));
Array
(
    [0] => 4
    [1] => 5
    [2] => 6
    [3] => 7
    [4] => 8
    [5] => 1
    [6] => 2
    [7] => 3
)
JAL
  • 21,295
  • 1
  • 48
  • 66
1

Just use the sum operator to merge the values of the two arrays, for instance:

$first = array(18, 20, 21, 28, 29);
$second = array(1, 8, 18, 19, 21, 22, 25, 28, 30); // Contains some elements of $first
$sum = $first + $second;

the resulting array shall contain the elements of both arrays, then you can filter out duplicates using array_unique $result = array_unique($sum);. At this point the resulting array will contain the elements of both arrays but just once:

Array
(
    [0] => 18
    [1] => 20
    [2] => 21
    [3] => 28
    [4] => 29
    [5] => 22
    [6] => 25
    [7] => 28
    [8] => 30
)
  • please refer to the linked related question. Your approach will omit existing **keys**. The value 1 is not a duplicate, yet it's missing from your resulting array, because `+` will only use the elements after the 5th from `$second` – Gordon Oct 15 '10 at 10:38
  • Yeah, that's typical PHP language design, making + behave differently from array_merge. However + has infrequent use cases, so good to keep in mind. – mario Oct 15 '10 at 10:50