array_unique with return of duplicate values and keys

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

array_unique with return of duplicate values and keys

Post by patrikG »

If you need to have the keys of the duplicates in an array returned, you may find this function useful:

Code: Select all

function unique($array){
   //checks $array for duplicate values and returns an
       //array containing the keys of duplicates
   $count= array_intersect_assoc($array, array_flip( array_count_values($array)));
   foreach($array as $key=>$value){
       if (in_array($value,$count)){
           $return[$value][]=$key;
       }
   }
   return $return;
}
Example:

Input:
function unique(array(44,23,23,23,9,9,9,9,9,9,9,9));

Function returns:
Array
(
[23] => Array
(
[0] => 1
[1] => 2
[2] => 3
)

[9] => Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 7
[4] => 8
[5] => 9
[6] => 10
[7] => 11
)
)
Post Reply