k7lluq
Last Updated: February 25, 2016
·
3.045K
· tobiasdeardorff
1292414 10152797588578902 4429100343119771489 o

Remove duplicate values from a simple array

In php there are a few ways to create an array of unique values from an existing array. The simplest and most readable way to create an array of unique values as a developer is array_unique, but this comes with some scalability problems as it's worst-case runtime becomes a hindrance as the array size grows.

The quickest way to achieve this is to use the array_flip function built-in to PHP[1]. array_flip will swap the array values with their keys and since an array cannot have duplicate keys you will end up with a unique set of keys that correspond to the values of the original array. To retrieve these keys as values you can use the array_keys function to retrieve your unique values.

Both array_flip and array_keys are worst-case O(n) functions while array_unique has a worst-case of O(n log(n)).[2]

$array = array(1, 2, 2, 3, 5, 8, 9, 1, 3);
$unique = array_keys(array_flip($array));

In order for this to work the array values must be strings or integers. Essentially the array values must also be able to represent an array key.

[1] http://www.php.net/manual/en/function.array-unique.php#70786
[2] http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip

Say Thanks
Respond