Sorting and counting is faster that finding unique values

Sorting and counting is faster that finding unique values

array_unique function is a native function that will extract distinct values in an array. array_count_values is also a native function that will extract distinct values in an array, and count the number of occurrences.

array_count_values actually does a lot more work than array_unique by providing a count of the distinct values, on top of finding them. Indeed, extracting the keys from the result of array_count_values removes the counts, and is the same result than array_unique.

<?php

$a = array('a', 'b', 'c', 'b', 'c', 'c');

print_r(array_unique($a));
//array('a', 'b', 'c');

print_r(array_keys(array_count_values(($a)));
//array('a', 'b', 'c');

?>

The strange fact is that array_count_values is a lot faster than array_unique. It may be twice as fast for small arrays (with tens of values), and it get even faster as the size of the array grows. Some, like puremango finally resorted to coding their own function in PHP, achieving much higher speed.

The only limitations are that array_count_values can only count string and integer values (as the PHP error will show if some other type is used), and array_unique includes a sorting option.

Avoid array_unique as much as possible and it will speed up your code execution. You may use the array_count_values, as it is the fastest code, but it is also possible to use other fast alternatives : foreach with array_keys, or array_flip (benchmark in this article : ‘array_unique vs array_flip‘).