user2619159
user2619159

Reputation: 23

Find duplicate values in an array which creates a new array with key as duplicate keys and values as the dupes

I am trying to find all duplicates in my array, and create a new array which has keys as the duplicate values key and value as the key of its duplicate

example

[1] => 10
[2] => 11
[3] => 12
[4] => 12
[5] => 12
[6] => 13
[7] => 13

After I apply the duplicate check I just need

[4] => [3] // value of key 4 is dupe of key 3
[5] => [3] // value of key 5 is dupe of key 3
[7] => [6] // value of key 7 is dupe of key 6

this gets me all duplicate keys, but I need duplicate keys with values as the keys which are duplicate

$arr_duplicates = array_keys(array_unique( array_diff_assoc( $array, array_unique( $array ) ) ));

Thanks

Upvotes: 2

Views: 470

Answers (2)

user2609094
user2609094

Reputation:

Try this for potential speed boost over the other solution. Will however use a lot more memory on large data sets.

<?php

$orig = array(
    1   => 10,
    2   => 11,
    3   => 12,
    4   => 12,
    5   => 12,
    6   => 13,
    7   => 13
);

$seen  = array();
$dupes = array();

foreach ($orig as $k => $v) {
    if (isset($seen[$v])) {
        $dupes[$k] = $seen[$v];
    } else {
        $seen[$v] = $k;
    }
}
unset($seen);

var_dump($dupes);

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227310

This should do what you want. Loop over the array, and see if the value was already in there. If so, add it to the result.

$arr_duplicates = array();
foreach($array as $k=>$v){
    // array_search returns the 1st location of the element
    $first_index = array_search($v, $array);
    // if our current index is past the "original" index, then it's a dupe
    if($k != $first_index){
        $arr_duplicates[$k] = $first_index;
    }
}

DEMO: http://ideone.com/Kj0dUV

Upvotes: 1

Related Questions