Delete repeated words from an array and sort it

2

I have a certain function that returns me array cluttered with multiple cities repeated. 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 a function that excludes the repeated city from the array and successively sorts this same array ? If not, what would be the feasible method for this case?

    
asked by anonymous 09.01.2017 / 22:34

1 answer

6

To remove repeated values:

array_unique( $array );

To order:

sort( array &$array );

Also, if you want to ignore case, and consider numbers by their total value and not by the digits, you have this:

natcasesort( array &$array );


Note that array_unique returns array without repeats, but sort and natcasesort (as well as almost any sort function of PHP) sort the array in place and returns a boolean.

That is, this does not work here:

$ordenado = sort( $unico );

simply because the array is not returned by the function. The change is made directly to $unico passed. (note that in documentation, when a parameter is prefixed by & , it means that it is passed by reference, which is a strong indication that it can be modified in the destination).

To do both, it might look 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 at IDEONE .

Internationalization: Using UTF-8 and collation

You will probably need something more complex, which will sort accented characters correctly according to the language used. For these scenarios, PHP has a specific collection of functions:

  

link

What we care about is the Collator . Here's an example use:

$cidades = array_unique( $cidades );

$coll = collator_create( 'pt_BR' );
collator_sort( $coll, $cidades);
    
09.01.2017 / 22:43