Get the keys for duplicate values in an array

function get_keys_for_duplicate_values($my_arr, $clean = false) {
    if ($clean) {
        return array_unique($my_arr);
    }

    $dups = $new_arr = array();
    foreach ($my_arr as $key => $val) {
      if (!isset($new_arr[$val])) {
         $new_arr[$val] = $key;
      } else {
        if (isset($dups[$val])) {
           $dups[$val][] = $key;
        } else {
           $dups[$val] = array($key);
           // Comment out the previous line, and uncomment the following line to
           // include the initial key in the dups array.
           // $dups[$val] = array($new_arr[$val], $key);
        }
      }
    }
    return $dups;
}

obviously the function name is a bit long;)

Now $dups will contain a multidimensional array keyed by the duplicate value, containing each key that was a duplicate, and if you send “true” as your second argument it will return the original array without the duplicate values.

Alternately you could pass the original array as a reference and it would adjust it accordingly while returning your duplicate array

Leave a Comment