$array = array(1, '1a', '1');
var_export(array_unique($array, SORT_REGULAR));
What is the logic behind this ? Why or how is '1a' excluded ?
This happens because array_unique
works by first sorting the values as strings, then iterating over the sorted array and for each value excluding from the result all successive values that compare equal to it.
The comparison function for "comparing equal" above is chosen according to the second parameter, which for SORT_REGULAR
is the same as an equality check with ==
.
This behavior gives rise to a whole lot of gotchas. Since the sort is quicksort, it's unstable. Therefore sorting an array that contains both 1
and '1'
gives no guarantee which one will end up being first in the result. This means that array_unique
may appear to arbitrarily "prefer" 1
in some cases and '1'
in others.
However the madness continues: consider that if the sort produces [1, '1', '1a']
then '1a'
will not be included in the result (it compares equal to 1
) while if the sort produces ['1', 1, '1a']
then it will be included (it does not compare equal to the string '1'
)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With