Home > Software engineering >  Remove duplicate rows from array even if their element ordering is different
Remove duplicate rows from array even if their element ordering is different

Time:10-21

in PHP how to get this unique of array ?

$originalArray = [[2,48],[48,2],[19,31],[31,19]];

I want to get

Array
(
    [0] => Array
        (
            [0] => 2
            [1] => 48
        )

    [2] => Array
        (
            [0] => 19
            [1] => 31
        )

)

I tried with array_unique($array,SORT_REGULAR) but still won't work. Is there other function to achieve this ?

CodePudding user response:

Similiar to this technique. Use sorted, stringified keys to build the filtered result.

Code: (Demo)

$array = [[2,48],[48,2],[19,31],[31,19]];

$result = [];
foreach ($array as $row) {
    sort($row);
    $result[json_encode($row)] ??= $row;  // just = will also work
}
var_export(array_values($result));
  • Related