H
H
Hint2011-11-14 11:39:43
PHP
Hint, 2011-11-14 11:39:43

PHP: Should the array_unique function sort the elements of an array?

Should the array_unique function sort the elements of an array? I never thought about it, but now it took mandatory preservation of order (I decided to get into the documentation to make sure).

php.net/manual/en/function.array-unique.php

array_unique() sorts the values ​​treated as string at first, then will keep the first key encountered for every value, and ignore all following keys.


Test: Result: So should the order be preserved or not?
<?php
$a = array('s3', 's1', 's3', 's2');
$a = array_unique($a);
print_r($a);
?>


Array ( [0] => s3 [1] => s1 [3] => s2 )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2011-11-14
@Palehin

" array_unique() takes an array as a parameter and returns a new array with no duplicate values.
Note that the keys are preserved. array_unique() first sorts the values ​​as strings, stores the first key it encounters for each value, and ignores all subsequent keys. This does not mean that the first key of each value of the unsorted array will be preserved.
"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question