Page 1 of 1

remove unique values from array?

Posted: Thu Jan 15, 2004 11:57 pm
by daveheinzel
I know of the function array_unique that removes duplicate values. However I need to have an array stripped of its values that only appear once in the array.

example:
array1( [0] => apple, [1] => orange, [2] => orange, [3] => cheese )

I would need a resulting array like:
array2( [1] => orange, [2] => orange )

The keys do NOT matter at all - they could remain as they were in the original array, or they could be recreated. Whatever works.

I'll probably run the stripped-down array through array_unique so I end up with an array listing the duplicate items in the original array.

Thanks-
Dave

Posted: Fri Jan 16, 2004 12:21 am
by lazy_yogi
untested .. but should be ok I think
(famous last words =P)

Code: Select all

function remove_unique($arr)
{
    $dict = array(); // dictionary
    foreach ($arr as $element)
    {
        $dict[$element]++;
    }

    $only_duplicates = array();
    foreach($dict as $key => $value)
    {
        if ($value > 1) $only_duplicates[] = $key;
    }

    return $only_duplicates;
}



$arr = array( "apple", "orange", "orange", "cheese" );
$arr = remove_unique($arr);
foreach($arr as $element)
{
    print $element;
}

looks good to me

Posted: Fri Jan 16, 2004 12:49 am
by daveheinzel
lazy_yogi,

Thank you very much! That looks like it should work. I am going to test it out a little later - it's late and I'm going to bed. I'll post another followup if something in the code needs to be changed.

later-
Dave

Posted: Fri Jan 16, 2004 3:10 am
by McGruff
Another idea:

Code: Select all

<?php

function findDupes($target) 
{
    $dupes = array();

    while(!is_null($value = array_shift($target)))
    {
        if(in_array($value, $target) and !in_array($value, $dupes))
        {
            $dupes[] = $value;
        }
    }
    return $dupes;
}

?>