$arr = asort($arr);
//some magic code goes here, $arr is not changed
$arr = array_unique($arr);
Should I use asort again to be sure $arr
is asorted?
My tests show that no, I don't. But I'm not sure for 100% if array_unique
actually removes the 2nd+ repeated elements.
You merely want to ensure that
asort
andarray_unique
use the same sort_flags.By default:
So you can see that each will sort based on a different algorithm, which might mostly match up, but you want it to explicitly match up. Thus, the smart money is on making a decision like:
Resulting in:
Also note that if you merely run
array_unique
without the initialasort
, you will get different results.Finally note that
asort
supports two flags thatarray_unique
does not support:SORT_NATURAL
- compare items as strings using "natural ordering" like natsort()SORT_FLAG_CASE
- can be combined (bitwise OR) withSORT_STRING
orSORT_NATURA
L to sort strings case-insensitivelyIf you use either of these two in your
asort
then you would necessarily need toasort
again afterarray_unique
.