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)
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
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With