One of my favorite features of PHP is the tremendous wealth of built-in functions that perform all kinds of useful tasks. Practically any basic operation I ever need to do can be done with a simple PHP function call. This was the case when I needed to remove duplicate values from an array of strings. array_unique() to the rescue.
However, it turns out that for simple dupe removal operations, there are alternatives to array_unique() that perform noticeably faster.
To replace array_unique(), try this faster alternative:
array_flip(array_flip($array))
Note that both functions above leave “gaps” in the resulting array; if $array[2] is a dupe and removed, $array[3] does NOT become $array[2]. If you’d like to reindex/reorder the resulting array, try
array_values(array_unique($array))
And here’s a faster alternative: (source)
array_keys(array_flip($array))
If you’d like to remove case insensitive duplicates, try the following function: (source)
function array_iunique($array) { return array_intersect_key($array,array_unique( array_map(strtolower,$array))); }
Or this faster alternative:
function array_iunique($array) { return array_intersect_key($array, array_flip(array_flip(array_map(strtolower,$array)))); }
Sorry for the really infrequent updates. 3-4 hour commutes per day and long work hours is killing my free time.
Merry Christmas to all!
If you liked this post, please subscribe to my feed. Thanks for visiting!


0 Responses to “Remove duplicate values from array: array_unique() variations and alternatives”