How To Check If PHP Array Contains Duplicates

February 28th, 2013 - Posted by Steve Marks to PHP, Web Development.

I just had to perform a check in PHP to detect whether duplicates existed in a given array. My first thought was to do some fancy looping and sorting of the array but I then came up with the following function and thought I’d share it:

function arrayContainsDuplicate($array)
      return count($array) != count(array_unique($array));  

The function is checking the number of elements in the array, and then comparing it to the number of elements once the array has been passed through the array_unique() function. If the numbers match, the function will return false, in which case we can safely assume that the array does not contain duplicates, and vice versa.

There are a number of ways this could be done but I found this quick and easy to use, with little code.

This entry was posted on Thursday, February 28th, 2013 at 11:12 am by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first