0

Possible Duplicate:
PHP merge array(s) and delete double values

I need to merge two arrays. I know I can use the array_merge function.

But it displays all the elements in both the arrays. But I need to replace all the similar values with a single value instead of all the values.

For example

$array1 = array("2", "3", "4");
$array2 = array("2", "7", "8");

If I use the array_merge function above the output will be 2,3,4,2,7,8 but I want it to be 2,3,4,7,8. I mean the value two should not repeat again. I hope there is a function to do my task. Please point it out to me

Community
  • 1
  • 1
Srivathsan
  • 600
  • 3
  • 9
  • 19

6 Answers6

8

First use array_merge, then use array_unique.

Ben F
  • 336
  • 1
  • 10
  • 1
    When including function names in inline code it is a nice touch to wrap the backticked function names in a link to its PHP doc page. The best part is you don't even have to google for the URL. Click the create link button and place `php.net/(function name)` after the `http://`. – Bailey Parker Jun 18 '12 at 12:34
  • @PhpMyCoder: Thanks, I didn't know if I could link code blocks, so now I know. – Ben F Jun 18 '12 at 12:38
3
function array_fusion($ArrayOne, $ArrayTwo)
{
    return array_unique(array_merge($ArrayOne, $ArrayTwo));
}
Chris
  • 4,255
  • 7
  • 42
  • 83
1
array_unique ( array_merge($array1,$array2));
Bailey Parker
  • 15,599
  • 5
  • 53
  • 91
FabioCosta
  • 3,069
  • 6
  • 28
  • 50
  • When writing code in an answer or post on SO, be sure to indent it with four spaces so that it is recognized as such and is properly highlighted. – Bailey Parker Jun 18 '12 at 12:31
1

You could use the following function :

$result = array_unique($input);

This will remove the duplicate values in your $input array. So apply the array_merge first, then the array_unique function i think.

Haroon
  • 1,125
  • 1
  • 11
  • 13
0

use it the way you do now but on the line after the merts use http://php.net/manual/en/function.array-unique.php

0

Just in case anyone ever finds this useful or is simply curious, you can also do two array flips. the first flip causes dupes to drop out when it creates unique keys from the values. Flipping again restores it to something useful. PHP always has numerous ways to get things done.

$arrays = array_flip(array_flip(array_merge($array1,$array2)));

Granted, array_unique is the more elegant and correct way to do this.

$arrays = array_unique(array_merge($array1,$array2));
EmmanuelG
  • 1,051
  • 9
  • 14