Quantcast
Channel: BIOSTALL » PHP
Viewing all articles
Browse latest Browse all 57

How To Check If PHP Array Contains Duplicates

$
0
0

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.


Viewing all articles
Browse latest Browse all 57

Trending Articles