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
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 |
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);
?>