krsort

(PHP 4, PHP 5, PHP 7, PHP 8)

krsortOrdena um array pelas chaves em ordem descrescente

Descrição

krsort(array &$array, int $flags = SORT_REGULAR): true

Ordena o array pelas chaves em ordem descrescente.

Nota:

Se dois elementos são comparados como iguais, eles mantêm sua ordem original. Antes do PHP 8.0.0, sua ordem relativa no array ordenado era indefinida.

Nota:

Redefine o ponteiro interno do array para o primeiro elemento.

Parâmetros

array

O array de entrada.

flags

O segundo parâmetro opcional flags pode ser usado para modificar o comportamento da ordenação usando estes valores:

Flags dos tipos de ordenação:

Valor Retornado

Sempre retorna true.

Registro de Alterações

Versão Descrição
8.2.0 O tipo do retorno agora é true; anteriormente, era bool.

Exemplos

Exemplo #1 Exemplo de krsort()

<?php
$frutas
= array("d"=>"limão", "a"=>"laranja", "b"=>"banana", "c"=>"maçã");
krsort($frutas);
foreach (
$frutas as $chave => $valor) {
echo
"$chave = $valor\n";
}
?>

O exemplo acima produzirá:

d = limão
c = maçã
b = banana
a = laranja

Veja Também

add a note add a note

User Contributed Notes 2 notes

up
-28
peter at pmkmedia dot com
20 years ago
Best deal sorting:

This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight.

Input: an array of unsorted weight/cost pairs
Output: none

function BEST_DEALS($myarray)
{   // most weight for least cost:
    // © Peter Kionga-Kamau, http://www.pmkmedia.com
    // thanks to Nafeh for the reversal trick
    // free for unrestricted use.
    krsort($myarray, SORT_NUMERIC);
    while(list($weight, $cost) = each($myarray))
    {   // delete bad deals, retain best deals:
        if(!$lastweight)
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
        else if($cost >= $lastcost) unset($myarray[$weight]);
        else
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
    }
    ksort($myarray);
}
up
-31
Anonymous
18 years ago
To create a natural reverse sorting by keys, use the following function:

<?php
function natkrsort($array)
{
   
$keys = array_keys($array);
   
natsort($keys);

    foreach (
$keys as $k)
    {
       
$new_array[$k] = $array[$k];
    }
  
   
$new_array = array_reverse($new_array, true);

    return
$new_array;
}
?>
To Top