How To Check If PHP Array Contains Duplicates
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.
0 comments:
Post a Comment