1

According to the PHP documentation, array_unique removes duplicate values and sorts the values treated as string at first.

When you take the following snippet in mind:

// define a simple array of strings, unordered
$brands = [ "BMW", "Audi", "BMW", "Chrysler", "Daewoo"];

// distinct the values, and sort them
echo array_unique($brands, SORT_STRING);

I would expect the output to be:

expected: {"0":"Audi","1":"BMW","3":"Chrysler","4":"Daewoo"}
actual  : {"0":"BMW","1":"Audi","3":"Chrysler","4":"Daewoo"}

The question is: why doesn't array_unique sort these values? Changing the sort_flags parameter to any of the four alternatives, or leaving it empty, has no effect either.

According to other SO questions, like "Why does array unique sort the values" I'm probably missing something obvious here. Also, using array_values(array_unique($brands)), as stated as an answer in this question doesn't seem to work either.

Update: As stated in the useful comments and answers, the sort_flags parameter is actually an inner compare behavior, or equality operator, sort of speak.

Community
  • 1
  • 1
Juliën
  • 9,047
  • 7
  • 49
  • 80
  • 3
    `array_unique` does **not sort** array elements. It just removes duplicate values from array. The manual is only mentioning the _sorts_ word regarding to internal (temporary) array processing. It doesn't mean real array sorting – hindmost Aug 23 '14 at 08:45
  • So, actually 'sort_flag' should really be interpreted as 'compare_behaviour'? If so, the naming convention and the forementioned posts confused me on this part. – Juliën Aug 23 '14 at 08:47
  • Also don't use `echo` with non-scalar values. – mickmackusa May 22 '23 at 22:29

2 Answers2

3

In manual they mean that values group by value and first key taken for eacj duplicated value.

you need something like this

$brands = array_unique($brands);
sort($brands);

SORT_STRING - is default

Dmitry Bezik
  • 349
  • 1
  • 5
  • 2
    You cannot call `sort` this way, BTW. – deceze Aug 23 '14 at 08:48
  • `sort` doesn't return the sorted array, it returns a boolean indicating whether it was successful. It relies on the array being passed by reference, which I don't think is compatible with using the result of a function. – Tom Fenech Aug 23 '14 at 08:52
  • this works though: `$brands = array_unique($brands); sort($brands);` – Nightwhistle Aug 23 '14 at 08:54
2

The documentation simply specifies how the algorithm is working internally to achieve its purpose. Why and how is well explained in the other question. It does not say that the returned result will be sorted as well. Sorting is outside the scope of this function and probably actually undesired most of the time.

For completeness, this is how'd you unique (is that a verb?) and sort the array:

$array = array_unique($array);
sort($array);
Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889