Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep unique values of array, preserving order, retaining last occurrence of each

Tags:

arrays

php

I have this array:

array(0, 3, 4, 3, 6);

And I want to filter out doubles, but keep the last result

array_unique gives me 0, 3, 4, 6.. but I need it to give 0, 4, 3, 6 (so it keeps the last 3, instead of the first)

like image 241
Sander Avatar asked May 27 '13 16:05

Sander


2 Answers

Just reverse it :

// Reverse an array, starting backwards
function array_unique_end($array)
{
  return array_reverse(array_unique(array_reverse($array)));
}

That however will not be very performant. You might be better off creating your own implementation

like image 80
Ven Avatar answered Sep 29 '22 08:09

Ven


This would be one way, traversing the array backwards:

$arr = array(0, 3, 4, 3, 6);

$res = array();
for ($i = count($arr) - 1; $i >= 0; --$i) {
        $item = $arr[$i];

        if (!isset($res[$item])) {
                $res = array($item => $item) + $res; // unshift
        }
}
print_r(array_values($res));

I've made a trade off between speed and memory by using an intermediate map, so that isset() can be used, from which the values (or keys) can be stripped to form the final result.

Update

It outperforms the double array_reverse() and array_unique() approach as the array becomes larger, so it's not that bad after all :)

like image 31
Ja͢ck Avatar answered Sep 29 '22 09:09

Ja͢ck