Should I use asort after array_unique if the array was asorted before?

245 Views Asked by At
$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.

4

There are 4 best solutions below

0
On BEST ANSWER

You merely want to ensure that asort and array_unique use the same sort_flags.

By default:

  • array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
  • bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

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:

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
asort($input,SORT_REGULAR);
print_r($input);
print "\n";
$result = array_unique($input,SORT_REGULAR);
print_r($result);

Resulting in:

 Array
(
    [1] => blue
    [a] => green
    [b] => green
    [2] => red
    [0] => red
)

Array
(
    [1] => blue
    [a] => green
    [2] => red
)

Also note that if you merely run array_unique without the initial asort, you will get different results.

Finally note that asort supports two flags that array_unique does not support:

  1. SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  2. SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

If you use either of these two in your asort then you would necessarily need to asort again after array_unique.

0
On

If you do not modify the array after the 'asort()', the array will be ordered.

0
On

No, you shouldn't. The function array_unique preserves keys, so there is no need to sort it again.

0
On

No you do not need to. array_unique will only remove elements, so the order will always be preserved.