tags:

views:

56

answers:

2

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 element.

+6  A: 

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;'));
BoltClock
Just like the one I was just typing. I'd like to add, though, if the array is large enough, they should set a counter and use a for loop.
Codeacula
we can't do anything to avoid looping?????
Ajith
@Ajith: included a non-loop solution.
BoltClock
You can use array_filter with a callback function that checks if the value is 1 if you really don't want to (write a) loop.
Leon
Your callbacks to `array_filter` don't check the value of `$x`.
salathe
@salathe: oops! Typo. I've fixed it, thanks.
BoltClock
+2  A: 

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));
salathe