Determing if an array has duplicate values in PHP

17 May, 2024

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 duplicate values removed. If any are removed, the resulting array will not be the same size as the original.

Login or Register to Comment!