If I had an array of signed integers e.g:
Array
(
[0] => -3
[1] => 1
[2] => 2
[3] => 3
[4] => 3
)
To get unique values I would instinctively use array_unique
but after consideration I could perform array_flip
twice which would have the same effect, and I think it would be quicker?
array_unique
O(n log n) because of the sort operation it uses
array_flip
O(n)
Am I correct in my assumptions?
UPDATE / EXAMPLE:
$intArray1 = array(-4,1,2,3);
print_r($intArray1);
$intArray1 = array_flip($intArray1);
print_r($intArray1);
$intArray1 = array_flip($intArray1);
print_r($intArray1);
Array
(
[0] => -3
[1] => 1
[2] => 2
[3] => 3
[4] => 3
)
Array
(
[-3] => 0
[1] => 1
[2] => 2
[3] => 4
)
Array
(
[0] => -3
[1] => 1
[2] => 2
[4] => 3
)
Caution: this technique is NOT a drop-in replacement for array_unique(). It only works for arrays with values that are are valid keys. (eg: string, integer, things can can be cast to int). And certainly does not work for arrays of objects.
vs:
you would have to use
which would take more time
I would go for
array_unique
. It has the added benefit of explaining whats happening.I benchmarked it for you: CodePad
Your intuition on this was correct!
Output:
Note that
array_keys(array_flip($array))
will give a new key values in order, which in many cases may be what you want (identical except much faster toarray_values(array_unique($array))
), whereasarray_flip(array_flip($array))
is identical (except much faster) toarray_unique($array)
where the keys remain the same.Nothing is better than running your own benchmark.
Update: Array with 1000 elements.
So yes, your assumption was correct.