Thursday, April 9, 2009

get duplicate values from an array

<?php
// this one is more efficient.
function array_duplicates($arr) {
if (!is_array($arr)) {
return false;
}

$duplicates = array();

sort($arr);

$count = count($arr) - 1; // ### last index won't have duplicate.
for ($i = 0; $i < $count; $i++) {
if ($arr[$i] == $arr[$i+1]) {
$duplicates[] = $arr[$i];
$i++; // ### Skip next index.
}
}

return $duplicates;
}

function array_duplicates($array) {
if(!is_array($array))
return false;

$duplicates = array();

$unique = array_unique($array);

if(count($array) > count($unique)) {
for($i = 0; $i < count($array); $i++) {
if(!array_key_exists($i, $unique)) {
$duplicates[] = $array[$i];
}
}
}

return $duplicates;
}
?>

No comments: