1

I have an array like this

Array
(
    [0] => u1,u2
    [1] => u2,u1
    [2] => u4,u3
    [3] => u1,u3
    [4] => u1,u2
)

I want to remove similar values from the array I want an out put like

Array
    (
        [0] => u1,u2
        [1] => u4,u3
        [2] => u1,u3

    )

I tried to loop thru the input array, sort the value of the indexes alphabetically and then tried array_search to find the repeated values. but never really got the desired output

any help apprecated

zamil
  • 1,920
  • 4
  • 17
  • 32

5 Answers5

3

You cannot use array_unique() alone, since this will only match exact duplicates only. As a result, you'll have to loop over and check each permutation of that value.

You can use array_unique() to begin with, and then loop over:

$myArray = array('u1,u2', 'u2,u1', 'u4,u3', 'u1,u3', 'u1,u2');

$newArr = array_unique($myArray);
$holderArr = array();

foreach($newArr as $val)
{
    $parts = explode(',', $val);
    $part1 = $parts[0].','.$parts[1];
    $part2 = $parts[1].','.$parts[0];

    if(!in_array($part1, $holderArr) && !in_array($part2, $holderArr))
    {
        $holderArr[] = $val;
    }
}

$newArr = $holderArr;

The above code will produce the following output:

Array ( 
    [0] => u1,u2 
    [1] => u4,u3 
    [2] => u1,u3 
)
BenM
  • 52,573
  • 26
  • 113
  • 168
0

Use array_unique() PHP function:

http://php.net/manual/en/function.array-unique.php

Lkopo
  • 4,798
  • 8
  • 35
  • 60
0

Use the function array_unique($array)

Leo T Abraham
  • 2,407
  • 4
  • 28
  • 54
0
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

php manual

Bhavin Rana
  • 1,554
  • 4
  • 20
  • 40
0

since u1,u2 !== u2,u1

    $array=array('u1,u2','u2,u1','u4,u3','u1,u3','u1,u2');
    foreach($array as $k=>$v)
    {
        $sub_arr = explode(',',$v);
        asort($sub_arr);
        $array[$k] = implode(',',$sub_arr);
    }

    $unique_array = array_unique($array);

    //$unique_array = array_values($unique_array) //if you want to preserve the ordered keys
rAjA
  • 899
  • 8
  • 13