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.

3
  • 2
    It's getting the count of each element... so what's it doing wrong? Commented Aug 27, 2010 at 11:12
  • Ah, I do now. There's not an easy way to do this: BoltClock's approach is probably best. Commented Aug 27, 2010 at 11:16
  • I figured it out. OP is asking to only filter out the keys which are reported as having duplicates in $arr1. Commented Aug 27, 2010 at 11:16

2 Answers 2

7

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;'));
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@Ajith: included a non-loop solution.
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.
Your callbacks to array_filter don't check the value of $x.
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.