PHP ksort() Function
What is the ksort() Function in PHP?
The ksort() function in PHP is used to sort an array by its keys in ascending order. It preserves the association between keys and values, meaning the keys remain associated with their respective values during the sorting process.
Syntax
ksort(array $array, int $sort_flags = SORT_REGULAR): bool
$array: The array to be sorted by key.$sort_flags: Optional. Defines the sorting behavior. The default isSORT_REGULAR, which compares items normally. Other options are:SORT_NUMERIC: Compare elements as numbers.SORT_STRING: Compare elements as strings.SORT_LOCALE_STRING: Compare elements as strings based on the current locale.
Examples
Example 1: Basic Usage
$array = [
"b" => "banana",
"a" => "apple",
"d" => "date",
"c" => "cherry"
];
ksort($array);
print_r($array);
Output:
Array
(
[a] => apple
[b] => banana
[c] => cherry
[d] => date
)
In this example, the array is sorted by keys in ascending alphabetical order.
Example 2: Sorting with SORT_NUMERIC
$array = [
3 => "three",
1 => "one",
2 => "two",
4 => "four"
];
ksort($array, SORT_NUMERIC);
print_r($array);
Output:
Array
(
[1] => one
[2] => two
[3] => three
[4] => four
)
Here, the array is sorted by numeric keys in ascending order.
Example 3: Sorting with SORT_STRING
$array = [
"10" => "ten",
"1" => "one",
"2" => "two",
"11" => "eleven"
];
ksort($array, SORT_STRING);
print_r($array);
Output:
Array
(
[1] => one
[10] => ten
[11] => eleven
[2] => two
)
In this example, the keys are treated as strings and sorted accordingly.
Example 4: Sorting with SORT_LOCALE_STRING
setlocale(LC_ALL, 'en_US.UTF-8');
$array = [
"apple" => "fruit",
"orange" => "fruit",
"cherry" => "fruit",
"banana" => "fruit"
];
ksort($array, SORT_LOCALE_STRING);
print_r($array);
Output:
Array
(
[apple] => fruit
[banana] => fruit
[cherry] => fruit
[orange] => fruit
)
In this case, the keys are sorted based on the current locale, which can affect string comparison (e.g., case sensitivity or accent characters).
Summary
ksort()sorts an array by its keys in ascending order.- It maintains key-value associations.
- Optional sorting behavior can be controlled using
SORT_*flags, such asSORT_NUMERIC,SORT_STRING, andSORT_LOCALE_STRING.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
