Filter out duplicate values in array using php
Please help me to filter out only duplicate values in array using php.Consider,
$arr1 = array('php','jsp','asp','php','asp')
Here I would prefer to print only
array('php'=>2,
'asp'=>2)
tried it by
print_r(array_count_values($arr1));
but, its getting count of each elem开发者_StackOverflow中文版ent.
OK, after the comments and rereading your question I got what you mean. You're still almost there with array_count_values()
:
$arr1 = array('php','jsp','asp','php','asp');
$counts = array_count_values($arr1);
You just need to remove the entries that are shown as only occurring once:
foreach ($counts as $key => $val) {
if ($val == 1) {
unset($counts[$key]);
}
}
EDIT: don't want a loop? Use array_filter()
instead:
// PHP 5.3+ only
$counts = array_filter($counts, function($x) { return $x > 1; });
// Older versions of PHP
$counts = array_filter($counts, create_function('$x', 'return $x > 1;'));
If you don't want the counts, a simpler way would be to do:
$arr1 = array('php','jsp','asp','php','asp');
$dups = array_diff_key($arr1, array_unique($arr1));
精彩评论