...

View Full Version : Pinpoint duplicates in array and change them



grumpy
02-12-2010, 06:23 PM
I have a one dimensional array of integers (single and double digit full numbers).

I would like to detect the presence of duplicate numbers, then identify all the elements of the array that are duplicates, return and extract them and change these duplicate numbers one by one to different numbers, based on my rules, re-insert the new numbers into the original array (that now has only unique numbers left in it) and keep checking for duplicates and changing the numbers until all array elements are unique.

I have tried array_intersect, but that only returns the values of the duplicates not all the elements that are duplicates and tried playing around with array_count_values but that didn't produce either.

Thanks for badly needed insights...

Thank you very much :)

Bo

Fou-Lu
02-12-2010, 06:56 PM
To first remove the duplicates, use the array_unique() function. This will return a new array minus the duplicates.
Next, find you're duplicates by using array_diff(). The order of arrays is important, you will need to provide the original array as the first argument, and the unique array as the second. That should return an array with all of the duplicate values, but its stability is questionable (as in, I don't know which specific elements it will choose for the duplicates - it could be the first, or last of any duplicate group). This is unlikely to matter unless you're tracking with keys that have some type of importance.

The solution I would actually take is to not allow them in the first place. Arrays in PHP are not controllable, but you can use an array object to you're advantage (5.2+).

grumpy
02-12-2010, 07:17 PM
The solution I would actually take is to not allow them in the first place. Arrays in PHP are not controllable, but you can use an array object to you're advantage (5.2+).

You are 100% right. I think I better validate the numbers when they are created to each other instead of removing duplicates at the end. Much easier and more full-proof. Wonderful. Thank you for the great idea!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum