RE: [PHP] Antithesis to array_unique
| From: | Ford, Mike [LSS] | Date: | Wed, 09 Jul 2003 14:58:21 +0000 |
| Subject: | RE: [PHP] Antithesis to array_unique | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-154564@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: David Nicholson [mailto:me@djnicholson.com]
> Sent: 09 July 2003 15:08
>
> This is a reply to an e-mail that you wrote on Wed, 9 Jul
> 2003 at 14:55,
> lines prefixed by '>' were originally written by you.
> > Having STFM I am wondering if anyone knows of a quick antithesis to
> > array_unique? We have an array in which we need to return all
> > duplicate
> > values instead of the non-duplicates.=20
>
> How about:
>
> $array1 = array("dupe","dupe","another item");
> $valuecount = array();
> foreach($array1 as $value){
> if(isset($valuecount[$value])){
> $valuecount[$value]++;
> } else {
> $valuecount[$value] = 1;
> }
> }
> $dupes = array();
> foreach($valuecount as $value=>$count){
> if($count>1){
> array_push($dupes,$value);
> }
> }
> // $dupes now contains all duplicate values.
>
> There may be a quicker way of doing it though...
Well, for a kick-off, how about making use of array_count_values()
(http://www.php.net/array_count_values)?
$array1 = array("dupe","dupe","another item");
$dupes = array();
foreach(array_count_values($array1) as $value=>$count){
if($count>1){
$dupes[] = $value;
}
}
I think judicious applications of array_unique() and array_diff() could also do the job, although I
don't know how this compares for efficiency:
$dupes = array_unique(array_diff($array1, array_unique($array1)));
Cheers!
Mike
---------------------------------------------------------------------
Mike Ford, Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Beckett Park, LEEDS, LS6 3QS, United Kingdom
Email: m.ford@lmu.ac.uk
Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211