Determing if an array has duplicate values in PHP

Recently, I had the need to determine whether an array had duplicate values in it. It didn't matter what the duplicate values were, or how many duplicates there were, either of which can be answered with array_count_values(), I just needed to know whether there were any at all; a boolean answer.

There are a lot of ways to approach it, but I found this to be the the most minimal:

$temp_array = array_unique($original_array);
$duplicates = sizeof($temp_array) != sizeof($original_array);

How this works is that array_unique() returns an array with all dupliate values removed. If any are removed, the resulting array will not be the same size as the original.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Of course, the Drupal Community isn't the only place to give back. It's a complex world, and there are as many worthy causes as their are melodies, with most being served by multiple charitable organizations. Here are a few of those that strike a 7th chord with me.