Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out duplicate values in array using php

Tags:

arrays

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

like image 382
Aadi Avatar asked Sep 01 '26 11:09

Aadi


1 Answers

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;'));
like image 175
BoltClock Avatar answered Sep 04 '26 01:09

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!