PHP Function Reference

PHP ksort() Function



The PHP ksort() function is used to sort an array in ascending order, according to the key and maintaining key to value association. This is useful mainly for associative arrays.

Syntax

ksort(array, flags)

Parameters

array Required. Specify the array to sort.
flags Optional. Specify sorting type flags to modify the sorting behavior. Sorting type flags:
  • SORT_REGULAR - Default. Compare items normally.
  • SORT_NUMERIC - Compare items numerically.
  • SORT_STRING - Compare items as strings.
  • SORT_LOCALE_STRING - Compare items as strings, based on current locale.
  • SORT_NATURAL - Compare items as strings using natural ordering.
  • SORT_FLAG_CASE - Compare items as strings and case-insensitive. Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL.

Return Value

Returns true on success and false in failure.

Exceptions

NA.

Example:

In the example below, ksort() function is used to sort an associative array in ascending order, according to the key.

<?php
$MyArray = array("Marry"=>25, 
                 "John"=>30, 
                 "Jo"=>45, 
                 "Kim"=>22, 
                 "Adam"=>35);
ksort($MyArray);

print_r($MyArray);
?>

The output of the above code will be:

Array
(
    [Adam] => 35
    [Jo] => 45
    [John] => 30
    [Kim] => 22
    [Marry] => 25
)

Example:

Consider one more example where this function is used to sort an associative array using case-insensitive natural ordering.

<?php
$Arr = array("Color1"=>"Red",
             "color2"=>"Green",
             "Color3"=>"Blue",
             "Color20"=>"White");

ksort($Arr, SORT_NATURAL | SORT_FLAG_CASE);

print_r($Arr);
?>

The output of the above code will be:

Array
(
    [Color1] => Red
    [color2] => Green
    [Color3] => Blue
    [Color20] => White
)

❮ PHP Array Reference