Ordenando Arrays

O PHP tem muitas funções para lidar com ordenação de arrays, e esse documento existe para ajudar a você lidar com elas.

As principais diferenças são:

  • Algumas ordenam com base nas chaves do array, enquanto outras pelos valores: $array['chave'] = 'valor';
  • A correlação entre as chaves e os valores do array não são mantidas depois da ordenação, o que pode fazer com que as chaves sejam resetadas numericamente (0, 1, 2, ...)
  • A ordem da ordenação: alfabética, menor para maior (ascendente), maior para menor (descendente), numérica, natural, aleatório, ou definida pelo usuário
  • Nota: Todas essas funções agem diretamente na própria variável do array, ao invés de retornar um novo array ordenado
  • Se qualquer uma dessas funções avaliar dois membros como iguais então a ordem será indefinida (a ordenação não é estável).

Atributos das funções de ordenação
Nome da função Ordena por Mantém a associação de chaves Ordem da ordenação Funções relacionadas
array_multisort() valor associativo sim, numérico não primeiro array ou opções de ordenação array_walk()
asort() valor sim menor para maior arsort()
arsort() valor sim maior para menor asort()
krsort() chave sim maior para menor ksort()
ksort() chave sim menor para maior asort()
natcasesort() valor sim natural, não sensível a maiúsculas natsort()
natsort() valor sim natural natcasesort()
rsort() valor não maior para menor sort()
shuffle() valor não random array_rand()
sort() valor não menor para maior rsort()
uasort() valor sim definido pelo usuário uksort()
uksort() chave sim definido pelo usuário uasort()
usort() valor não definido pelo usuário uasort()

add a note add a note

User Contributed Notes 3 notes

up
131
"Matthew Rice"
10 years ago
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.
up
25
oculiz at gmail dot com
13 years ago
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.
up
0
Hayley Watson
7 years ago
Stabilizing the sort functions (in this case, usort).

<?php
function stable_usort(&$array, $cmp)
{
   
$i = 0;
   
$array = array_map(function($elt)use(&$i)
    {
        return [
$i++, $elt];
    },
$array);
   
usort($array, function($a, $b)use($cmp)
    {
        return
$cmp($a[1], $b[1]) ?: ($a[0] - $b[0]);
    });
   
$array = array_column($array, 1);
}
?>

Tags each array element with its original position in the array so that when the comparison function returns 0 the tie can be broken to put the earlier element first.
To Top