remove unique values from array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
daveheinzel
Forum Newbie
Posts: 8
Joined: Tue Dec 02, 2003 10:47 pm

remove unique values from array?

Post 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
User avatar
lazy_yogi
Forum Contributor
Posts: 243
Joined: Fri Jan 24, 2003 3:27 am

Post 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;
}
daveheinzel
Forum Newbie
Posts: 8
Joined: Tue Dec 02, 2003 10:47 pm

looks good to me

Post 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
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post 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;
}

?>
Post Reply