What is the use of ksort() in PHP?

ksort() sorts an array by its keys in ascending order (A to Z, 1 to 9). It keeps the key and value pairs together. To sort the keys in reverse order use krsort().

<?php
$age = ["Robin" => 25, "Anil" => 30, "Zoya" => 22];

ksort($age);
print_r($age);
?>

Output:

Tutorials Class - Output Window

Array
(
[Anil] => 30
[Robin] => 25
[Zoya] => 22
)

<?php
$age = ["Robin" => 25, "Anil" => 30, "Zoya" => 22];

krsort($age);
print_r($age);
?>

Output:

Tutorials Class - Output Window

Array
(
[Zoya] => 22
[Robin] => 25
[Anil] => 30
)

Both functions sort the original array (they do not return a new one). To sort by value use asort() and arsort().


Learn more about the similar topics:
Tutorials
PHP Arrays
PHP Array Functions
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
What are the different PHP functions to sort an array?
PHP’s numerically indexed array begins with which position?
Which PHP function inserts an element to the end of an array?
Which PHP function can be used check if variable is an array?
How many types of arrays are available in PHP?
What is the use of array_chunk() function in PHP?
What is the use of in_array() function in PHP?