1

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

vxd
  • 11
  • 1

3 Answers3

2
$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.

Lars
  • 5,757
  • 4
  • 25
  • 55
1
$numbers = array_count_values($array);
$array = array_unique($array);
$array = array_merge($array, array_fill(1, $numbers['apple'], 'apple'));
powtac
  • 40,542
  • 28
  • 115
  • 170
0
$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);
Marc B
  • 356,200
  • 43
  • 426
  • 500