Skip to content
Advertisement

Remove A|B duplicates from associative array in Laravel

I have an associative array containing entries that are virtually the same, except the key-value pairs are swapped:

[
    [
        "partnerA" => "Alice",
        "partnerB" => "Alfred"
    ],
    [
        "partnerA" => "Alfred",
        "partnerB" => "Alice"
    ],
    [
        "partnerA" => "Alfred",
        "partnerB" => "Brandon"
    ]
]

I stored the array in a Laravel collection and tried using ->unique()

  $partners = collect($array)->unique();

but the output matches the array feeding in.

How can I remove duplicates like this from an array so each pair is unique no matter if the keys are swapped?

The desired output is:

[
    [
        "partnerA" => "Alice",
        "partnerB" => "Alfred"
    ],
    [
        "partnerA" => "Alfred",
        "partnerB" => "Brandon"
    ]
]

Update: What I’ve tried so far that seems to be working…

$size = sizeof($partners);
for($i = 0; $i <= $size; $i++){
    $match = $partners[$i];
    $needle = ["partnerA" => $match["partnerB"], "partnerB" => $match["partnerA"]];
            
    if(in_array($needle, $partners)){
        unset($partners[$i]);
    }
}

Advertisement

Answer

Sort the pairs and concatenate the values for a unique key, then filter based on the result.

$unique_keys = array_keys(array_unique(array_map(
    function($a){
        sort($a);
        return implode("", $a);
    },
    $partners
)));

$res = array_filter(
    $partners,
    function($a)use($unique_keys) {
        return in_array($a, $unique_keys);
    },
    ARRAY_FILTER_USE_KEY
);

var_dump($res);

Output:

array(2) {
  [0]=>
  array(2) {
    ["partnerA"]=>
    string(6) "Alfred"
    ["partnerB"]=>
    string(5) "Alice"
  }
  [2]=>
  array(2) {
    ["partnerA"]=>
    string(6) "Alfred"
    ["partnerB"]=>
    string(7) "Brandon"
  }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement