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.
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
.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.