php array_unique sorting behavior
Asked Answered
T

3

7

I am checking the array_unique function. The manual says that it will also sort the values. But I cannot see that it is sorting the values. Please 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 array $result is not sorted. Any help is appreciated.

Thank you Pramod

Tridactyl answered 16/8, 2014 at 7:21 Comment(1)
The manual doesn't say, that it is sorting values the second parameter is used for comparing the items.Claud
C
8

array_unique:

Takes an input array and returns a new array without duplicate values.

Note that keys are preserved. array_unique() keeps the first key encountered for every value, and ignore all 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);
Cluster answered 16/8, 2014 at 7:29 Comment(2)
Thank you Suchit for the clarification. I was a bit confused.Tridactyl
I don't know if your first language is English Pramod. Mine is, and I find the description confusing. The example shown above is excellent though.Sotos
I
5

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

The optional second parameter sort_flags may be used to modify the sorting behavior using these values: [...]

The sorting behavior is used to sort the array values in order to perform the comparison and determine whether one element is considered to be equal to another. It does not modify the order of the underlying array.

If you want to sort your array, you'll have to do that as a separate operation. Documentation on array sorting can be found here.

For a default ascending sort based on the array's values, you could use asort.

Ileac answered 16/8, 2014 at 7:26 Comment(0)
S
1

array_unique takes an input array and returns a new array without duplicate values. It doesn't sort actually. Read more at http://php.net/manual/en/function.array-unique.php

Slaby answered 16/8, 2014 at 7:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.