PHP dispone de numerosas funciones para ordenar arrays, y esta sección del manual va a ayudar a comprenderlas.
Las diferencias principales son:
$array['clave'] = 'valor';
| Nombre de la función | Ordenación por | Asociación clave-valor | Orden de ordenación | Funciones asociadas |
|---|---|---|---|---|
| array_multisort() | valor | claves string sí, claves int no | primer array, o bien opciones de ordenación | array_walk() |
| asort() | valor | sí | ascendente | arsort() |
| arsort() | valor | sí | descendente | asort() |
| krsort() | clave | sí | descendente | ksort() |
| ksort() | clave | sí | ascendente | asort() |
| natcasesort() | valor | sí | natural, insensible a la casilla | natsort() |
| natsort() | valor | sí | natural | natcasesort() |
| rsort() | valor | no | descendente | sort() |
| shuffle() | valor | no | aleatorio | array_rand() |
| sort() | valor | no | ascendente | rsort() |
| uasort() | valor | sí | Definido por una función de usuario | uksort() |
| uksort() | clave | sí | Definido por una función de usuario | uasort() |
| usort() | valor | no | Definido por una función de usuario | uasort() |
While this may seem obvious, user-defined array sorting functions ( uksort(), uasort(), usort() ) will *not* be called if the array does not have *at least two values in it*.
The following code:
<?php
function usortTest($a, $b) {
var_dump($a);
var_dump($b);
return -1;
}
$test = array('val1');
usort($test, "usortTest");
$test2 = array('val2', 'val3');
usort($test2, "usortTest");
?>
Will output:
string(4) "val3"
string(4) "val2"
The first array doesn't get sent to the function.
Please, under no circumstance, place any logic that modifies values, or applies non-sorting business logic in these functions as they will not always be executed.Another way to do a case case-insensitive sort by key would simply be:
<?php
uksort($array, 'strcasecmp');
?>
Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.