PHP ksort() Function (original) (raw)
Last Updated : 20 Jun, 2023
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:
bool ksort( array,array, 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.
Return Value: This function returns True on success or False on failure.
Below programs illustrate the ksort() function in PHP.
Program 1:
<?php
$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"
,
`` );
ksort(
$arr
);
foreach
(
$arr
as
$key
=>
$val
) {
`` echo
"[$key] = $val"
;
`` echo
"\n"
;
}
?>
Output:
[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
Program 2:
<?php
$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,
`` );
ksort(
$arr
);
foreach
(
$arr
as
$key
=>
$val
) {
`` echo
"[$key] = $val"
;
`` echo
"\n"
;
}
?>
Output:
[a] = 77 [b] = 66 [d] = 1 [e] = 56 [i] = 3 [m] = 2 [n] = 44 [o] = 55 [q] = -11 [x] = 33 [y] = 22 [z] = 11
Related Articles:
Reference: http://php.net/manual/en/function.ksort.php