---
title: "Avoid array_unique"
url: https://www.exakat.io/avoid-array_unique/
date: 2015-01-11
modified: 2025-01-22
author: "dams"
description: "[caption id=\"attachment_479\" align=\"alignleft\" width=\"331\"] Sorting and counting is faster that finding unique values[/caption] array_unique() is quite slow It is recommended to avoid array_unique. array_unique() function is a native function that..."
categories:
  - "Code auditing"
word_count: 303
---

# Avoid array_unique

[![Sorting and counting is faster that finding unique values](http://178.62.231.40/wp-content/uploads/2015/01/clippers.320.jpg)](http://178.62.231.40/wp-content/uploads/2015/01/clippers.320.jpg)Sorting and counting is faster that finding unique values

## array_unique() is quite slow

It is recommended to avoid array_unique. [array_unique()](http://www.php.net/array_unique) function is a native function that will extract distinct values in an array. [array_count_values](http://www.php.net/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.

Using the flag SORT_REGULAR, which makes direct comparisons of the values instead of convertir them to string (default) or integer (SORT_NUMERIC), is even slower.

## Alternatives to avoid array_unique()

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](http://www.puremango.co.uk/2010/06/fast-php-array_unique-for-removing-duplicates/) 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()

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](http://www.php.net/array_keys), or [array_flip](http://www.php.net/array_flip) (benchmark in this article : '[array_unique vs array_flip](http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip)'). Of course, relying on these alternatives degrades the readability of the code, since, after all, array_unique() is the eponymous feature. It's just a bit slow.