PHP ksort() Function
Last Updated :
11 Jul, 2025
Improve
The ksort() function is an inbuilt function in PHP which is used to sort an array in ascending order according to its key values. It sorts in a way that the relationship between the indices and values is maintained.
Syntax:
php
php
bool ksort( $array, $sorting_type )Parameters: This function accepts two parameters as mentioned above and described below:
- $array: This parameter specifies the array which needs to be sorted. It is a mandatory parameter.
- $sorting_type: This is an optional parameter. There are different sorting types which are discussed below:
- SORT_REGULAR: The value of $sorting_type is SORT_REGULAR then items are compare normally.
- SORT_NUMERIC: The value of $sorting_type is SORT_NUMERIC then items are compared numerically.
- SORT_STRING: The value of $sorting_type is SORT_STRING then items are compared as a string.
- SORT_LOCALE_STRING: The value of $sorting_type is SORT_STRING then items are compare as strings, based on the current locale.
<?php
// PHP program to illustrate
// ksort()function
// Input different array elements
$arr = array("13" =>"ASP.Net",
"12" =>"C#",
"11" =>"Graphics",
"4" =>"Video Editing",
"5" =>"Photoshop",
"6" =>"Article",
"4" =>"Placement",
"8" =>"C++",
"7" =>"XML",
"10" =>"Android",
"1" =>"SQL",
"2" =>"PL/Sql",
"3" =>"End",
"0" =>"Java",
);
// Implementation of ksort()
ksort($arr);
// for-Loop for displaying result
foreach ($arr as $key => $val) {
echo "[$key] = $val";
echo"\n";
}
?>
Output:
Program 2:
[0] = Java [1] = SQL [2] = PL/Sql [3] = End [4] = Placement [5] = Photoshop [6] = Article [7] = XML [8] = C++ [10] = Android [11] = Graphics [12] = C# [13] = ASP.Net
<?php
// PHP program to illustrate
// ksort function
// Input different array elements
$arr = array("z" => 11,
"y" => 22,
"x" => 33,
"n" => 44,
"o" => 55,
"b" => 66,
"a" => 77,
"m" => 2,
"q" => -11,
"i" => 3,
"e" => 56,
"d" => 1,
);
// Implementation of ksort
ksort($arr);
// for-Loop for displaying result
foreach ($arr as $key => $val) {
echo "[$key] = $val";
echo"\n";
}
?>
Output:
Related Articles:
Reference: https://www.php.net/manual/en/function.ksort.php
[a] = 77 [b] = 66 [d] = 1 [e] = 56 [i] = 3 [m] = 2 [n] = 44 [o] = 55 [q] = -11 [x] = 33 [y] = 22 [z] = 11