I have code that adds values to an array. The array is later searched in another part of my code. The values that are added to the array are not necessarily unique, so it\'s
I think array_unique
is slower than in_array
but it makes sense if you want to search the array more than one time or if you want to save memory.
Another option is to use array_flip (which will also drop duplicate keys) and then use isset
or array_key_exists
since they are way faster than in_array
, personally I would go this way.
This comment was worthy to be promoted to an answer:
Just found that
array_keys(array_flip($array));
is amazingly faster thanarray_unique();
. About 80% faster on 100 element array, 95% faster on 1000 element array and 99% faster on 10,000+ element array.
Testing here shows that with random (integer) strings which do contain array value repetition, that array_keys(array_flip($array));
method is orders of magnitude faster than other methods.
array_unique is about sqrt(n)
times slower then in_array. But if you optimize the data and search again many times, it can be worth
PS: notice that
isset($arr[$key])
works faster then in_array
providing the same result