Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check and return duplicates array php

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

like image 954
NVG Avatar asked Aug 10 '10 14:08

NVG


2 Answers

this will be ~100 times faster than array_diff

$dups = array(); foreach(array_count_values($arr) as $val => $c)     if($c > 1) $dups[] = $val; 
like image 180
user187291 Avatar answered Sep 20 '22 18:09

user187291


You can get the difference of the original array and a copy without duplicates using array_unique and array_diff_assoc:

array_diff_assoc($arr, array_unique($arr)) 
like image 36
Gumbo Avatar answered Sep 18 '22 18:09

Gumbo