Php sorting behavior array_unique

I am checking the array_unique function. The manual says that it also sorts the values. But I don’t see it sorting the values. See my sample code.

$input = array("a" => "green", 3=>"red", "b" => "green", 1=>"blue", "red"); print_r($input); $result = array_unique($input,SORT_STRING); print_r($result); The output is Array ( [a] => green [3] => red [b] => green [1] => blue [4] => red ) Array ( [a] => green [3] => red [1] => blue ) 

Here the $ result array is not sorted. Any help is appreciated.

Thanks. Pramod

+6
source share
3 answers

array_unique:

It takes an input array and returns a new array with no duplicate values.

Please note that the keys are saved. array_unique () first sorts the values ​​processed as a string, and then saves the first key for each value and ignores all of the following keys.

you can try this to get the result:

 <?php $input = array("a" => "green", 3=>"red", "b" => "green", 1=>"blue", "red"); print_r($input); $result = array_unique($input); print_r($result); asort($result); print_r($result); 
+6
source

manual does not say that it will sort the elements of the array, it says that the sort_flags parameters change the sorting behavior.

The optional second parameter sort_flags can be used to change the sort behavior using the following values: [...]

Sorting behavior is used to sort array values ​​to perform comparisons and determine whether one element is considered equal to another. It does not change the order of the underlying array.

If you want to sort the array, you have to do it as a separate operation. Array sorting documentation can be found here .

For incremental default sorting based on array values, you can use asort .

+4
source

array_unique takes an input array and returns a new array without duplicate values. This is actually not sorting. More details at http://php.net/manual/en/function.array-unique.php

+1
source

Source: https://habr.com/ru/post/973891/


All Articles