up vote 1 down vote favorite
share [g+] share [fb]

I want to remove duplicate values in an array except 1 value.

Eg:

$array = array ("apple", "orange", "orange", "banana", "grapes","grapes", "apple");

How can I remove all duplicate values and keep all duplicate values that equal "apple"

 $array = array ("apple", "orange", "banana", "grapes", "apple");

There are about 400 values

link|improve this question
You want to keep the position of apple or simply the number of occurrences? – powtac Aug 29 '11 at 22:37
feedback

3 Answers

$numbers = array_count_values($array);
$array = array_unique($array);
$array = array_merge($array, array_fill(1, $numbers['apple'], 'apple'));
link|improve this answer
feedback
$array = array ("apple", "orange", "orange", "banana", "grapes","grapes", "apple");

$counts = array_count_values($array);

$new_array = array_fill(0, $counts['apple']-2, 'apple'); // -2 to handle there already being an apple from the array_unique count below.
$new_array = array_merge(array_unique($array), $new_array);
link|improve this answer
:) got to the same answer :) – powtac Aug 29 '11 at 22:43
feedback
$seen = array()
foreach ($array as $value)
    if ($value == 'apple' || !in_array($value, $seen))
        $seen[] = $value;

$seen will now have only the unique values, plus the apple.

link|improve this answer
And the apples? What about the apples? – Marc B Aug 29 '11 at 22:39
clicked on update a second early, added the line right before your comment. ;) – Lars Aug 29 '11 at 22:40
Thanks, worked like a treat – vxd Aug 29 '11 at 22:50
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.