PHP ksort() function is “used to sort an array in ascending order based on its keys while maintaining the key-value relationships.”
Syntax
ksort($array, sorttype)
Parameters
$array(required): It is an input array.
$sorttype(optional): There are 6 different sorting types which are discussed below
- SORT_REGULAR(Default) – Compare elements normally without changing types
- SORT_NUMERIC – Compare elements numerically.
- SORT_STRING – Compare elements as strings.
- SORT_LOCALE_STRING – Compare elements as strings based on the current locale.
- SORT_NATURAL – Compare elements as strings using natural ordering.
Return value
It returns true(PHP 8.2.0), previously it returned bool.
Visual Representation
Example 1:How to Use ksort() Function
<?php
$stcast = [
'Millie' => 15,
'Finn' => 16,
'Noah' => 15,
'Gaten' => 16,
'Caleb' => 17
];
echo 'Before ksort'. "\n";
print_r($stcast);
ksort($stcast);
echo 'After ksort'. "\n";
print_r($stcast);
Output
Before ksort
Array
(
[Millie] => 15
[Finn] => 16
[Noah] => 15
[Gaten] => 16
[Caleb] => 17
)
After ksort
Array
(
[Caleb] => 17
[Finn] => 16
[Gaten] => 16
[Millie] => 15
[Noah] => 15
)
In the above example, ksort() function has sorted the keys alphabetically: ‘Caleb’ comes before ‘Finn’, followed by ‘Gaten’, ‘Millie’, and ‘Noah’. The corresponding values are preserved with their respective keys.
Example 2: Sorting the associative array by a specific key
<?php
$stcast = array(
array('name' => 'Millie', 'age' => 15),
array('name' => 'Finn', 'age' => 16),
array('name' => 'Caleb', 'age' => 17),
array('name' => 'Gaten', 'age' => 16),
array('name' => 'Noah', 'age' => 15),
);
function sortByName($a, $b)
{
$a = $a['name'];
$b = $b['name'];
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
function sortByAge($a, $b)
{
$a = $a['age'];
$b = $b['age'];
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
echo 'Sort by Name';
usort($stcast, 'sortByName');
print_r($stcast);
echo 'Sort by Age';
usort($stcast, 'sortByAge');
print_r($stcast);
Output
Sort by NameArray
(
[0] => Array
(
[name] => Caleb
[age] => 17
)
[1] => Array
(
[name] => Finn
[age] => 16
)
[2] => Array
(
[name] => Gaten
[age] => 16
)
[3] => Array
(
[name] => Millie
[age] => 15
)
[4] => Array
(
[name] => Noah
[age] => 15
)
)
Sort by AgeArray
(
[0] => Array
(
[name] => Millie
[age] => 15
)
[1] => Array
(
[name] => Noah
[age] => 15
)
[2] => Array
(
[name] => Gaten
[age] => 16
)
[3] => Array
(
[name] => Finn
[age] => 16
)
[4] => Array
(
[name] => Caleb
[age] => 17
)
)
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.