Facebook Page Twitter Page LinkedIn Page
× PHP Tutorial PHP Advanced PHP Resources


The PHP Array ksort() function is used to sort an associative array in ascending order, according to the key. The function has one optional parameter which can be used to specify sorting type. Please see below for more details.

Syntax

ksort(array, sorting_type)

Parameters

array Required. Specify the associative array to sort
sorting_type Optional. There are six sorting types which are mentioned below:

  • 0 or SORT_REGULAR - Default. Compare items normally.
  • 1 or SORT_NUMERIC - Compare items numerically.
  • 2 or SORT_STRING - Compare items as strings.
  • 3 or SORT_LOCALE_STRING - Compare items as strings, based on current locale.
  • 4 or SORT_NATURAL - Compare items as strings using natural ordering.
  • 5 or SORT_FLAG_CASE - Compare items as strings and case-insensitive.

Note: The | (bitwise operator) can be used to specify more than one sorting type, for example - 4|5.


Return Value

Returns TRUE on success and False in failure.

Exceptions

NA.

Example:

In the below example, ksort() function is used to sort an associative array called MyArray 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
)

❮ PHP Array functions