To remove repeated values:
array_unique( $array );
To order:
sort( array &$array );
And yet, if you want to ignore upper and lower case, and consider numbers by their total value and not by digits, you have this:
natcasesort( array &$array );
Note that the array_unique
returns the array without the repeated, but the sort
and natcasesort
(as well as virtually every PHP sorting function) sorts itself array "in place" and returns a boolean.
I mean, this doesn’t work:
$ordenado = sort( $unico );
for the simple fact that the array is not returned by the function. The change is made directly in the $unico
past. (note that in the documentation, when a parameter is prefixed by &
, means it is passed by reference, which is a strong indication that it can be modified at destination).
To do both, it can be something like this:
$cidades = array(
'são paulo',
'rio de janeiro',
'belo horizonte',
'recife',
'fortaleza',
'porto alegre',
'jurerê',
'belo horizonte'
);
$cidades = array_unique( $cidades );
natcasesort( $cidades );
// agora $cidades está em ordem e sem repetição
See working on IDEONE.
Internationalization: using UTF-8 and collation
Probably you in everyday life will need something more complex, which sort accented characters correctly according to the language used. For these scenarios, PHP has a specific collection of functions:
http://dk2.php.net/manual/en/book.intl.php
What we’re interested in is Collator. See an example of use:
$cidades = array_unique( $cidades );
$coll = collator_create( 'pt_BR' );
collator_sort( $coll, $cidades);
Cool. But what would be "array 'in place'"?
– viana
@Acklay didn’t make $sorted = Sort( $unico ) pq doesn’t work like that. Sort moves the original array, passed in the parameter, instead of returning a new one.
– Bacco
Very useful part of the additional "Internationalization". Thank you! I wanted to give +2;
– viana