PHP krsort() Function

Definition

The krsort() function takes an array and reverse sorts it by its keys while preserving the values.

This is the opposite of the ksort().

Syntax

PHP krsort() Function has the following syntax.

bool krsort ( array &arr [, int options] )

Parameter

ParameterIs RequiredDescription
arrRequired.Array to sort
optionsOptional.How to compare the array elements/items.

Possible values for options:

ValueDescription
0 = SORT_REGULARDefault. Compare items normally without changing types)
1 = SORT_NUMERICCompare items numerically
2 = SORT_STRINGCompare items as strings
3 = SORT_LOCALE_STRINGCompare items as strings, based on current locale
4 = SORT_NATURALCompare items as strings using natural ordering
5 = SORT_FLAG_CASEan be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

Note

Use the ksort() function to sort an associative array in ascending order, according to the key.

Use the arsort() function to sort an associative array in descending order, according to the value.


<?PHP//w w w .  ja va2 s .c o  m
    $capitalcities['A'] = 'Z';
    $capitalcities['B'] = 'X';
    $capitalcities['C'] = 'Y';
    krsort($capitalcities);
    print_r($capitalcities);
?>

krsort() directly changes the value you pass in. The return value is either true or false, depending on whether the sorting was successful.

The code above generates the following result.

Example 2

Sort an associative array in descending order, according to the key:


<?php
$age=array("PHP"=>"5","Java"=>"7","java2s.com"=>"9");
krsort($age);
?>

The krsort() function sorts an associative array in descending order, according to the key.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions