Check and return duplicates array php

NVG picture NVG · Aug 10, 2010 · Viewed 66.9k times · Source

I would like to check if my array has any duplicates and return the duplicated values in an array. I want this to be as efficient as possible.

Example:

$array = array( 1, 2, 2, 4, 5 );
function return_dup($array); // should return 2

$array2 = array( 1, 2, 1, 2, 5 );
function return_dup($array2); // should return an array with 1,2

Also the initial array is always 5 positions long

Answer

user187291 picture user187291 · Aug 10, 2010

this will be ~100 times faster than array_diff

$dups = array();
foreach(array_count_values($arr) as $val => $c)
    if($c > 1) $dups[] = $val;