Delete repeated words from an array and sort it

Asked

Viewed 405 times

2

I have a certain function that returns to me array disorderly with several repeated cities. This way:

<?php 

function getArrayCities() {
    return array("são paulo","rio de janeiro","belo horizonte","recife","fortaleza",
   "porto alegre","jurerê","belo horizonte");
}

echo var_dump(getArrayCities());

Is there any function that excludes repeated city’s array and successively orders this same array? If not, what would be the feasible method for this case?

1 answer

6


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'"?

  • @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.

  • Very useful part of the additional "Internationalization". Thank you! I wanted to give +2;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.