PHP ksort() Function

Definition

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

Syntax

PHP ksort() Function has the following syntax.

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

Parameter

ParameterIs RequiredDescription
arrayRequired.Specifies the array to sort
sortingtypeOptional.Specifies how to compare the array elements/items.

Possible values for sortingtype:

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 krsort() function to sort an associative array in descending order, according to the key.

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


<?PHP// w ww  . j  a  v  a  2 s .  c om
    $capitalcities['A'] = 'Z';
    $capitalcities['B'] = 'X';
    $capitalcities['C'] = 'Y';
    ksort($capitalcities);
    print_r($capitalcities);
?>

ksort() works by reference, directly changing the array. The return value is either true or false, depending on whether the sorting was successful.

The code above generates the following result.

Example 1

We can pass a second parameter to the sort functions to specify how you want the values sorted, like this:


<?PHP/*from   ww w.j  av  a  2s.  c o  m*/
    $array["1"] = "1";
    $array["2"] = "2";
    $array["3"] = "3";
    $array["10"] = "10";
    $array["100"] = "100";
    var_dump($array);
    ksort($array, SORT_STRING);
    var_dump($array);
?>

If you want to force a strictly numeric sort, you can pass SORT_NUMERIC as the second parameter.

The code above generates the following result.

Example 2

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


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




















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