The ksort()
function takes an array and sorts it by its keys while preserving the values.
PHP ksort() Function has the following syntax.
bool ksort ( array &arr [, int options] )
Parameter | Is Required | Description |
---|---|---|
array | Required. | Specifies the array to sort |
sortingtype | Optional. | Specifies how to compare the array elements/items. |
Possible values for sortingtype:
Value | Description |
---|---|
0 = SORT_REGULAR | Default. Compare items normally without changing types |
1 = SORT_NUMERIC | Compare items numerically |
2 = SORT_STRING | Compare items as strings |
3 = SORT_LOCALE_STRING | Compare items as strings, based on current locale |
4 = SORT_NATURAL | Compare items as strings using natural ordering |
5 = SORT_FLAG_CASE | an be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively |
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
$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.
We can pass a second parameter to the sort functions to specify how you want the values sorted, like this:
<?PHP//w w w. j a v a2 s . com
$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.
Sort an associative array in ascending order, according to the key:
<?php
$age=array("PHP"=>"5","Java"=>"7","java2s.com"=>"3");
ksort($age);
?>