How to use uksort() Function In PHP
The uksort() function allows you to sort an associative array by keys using a custom comparison function.
Example: This example shows the use of uksort() function.
<?php
$subjects = array(
"Maths" => 95,
"Physics" => 90,
"Chemistry" => 96,
"English" => 93,
"Computer" => 98
);
uksort($subjects, function($a, $b) {
return strcmp($a, $b);
});
foreach ($subjects as $key => $value) {
echo "$key => $value\n";
}
?>
Output
Chemistry => 96 Computer => 98 English => 93 Maths => 95 Physics => 90
Sort an Associative Array by Key in PHP
Given an Associative Array, the task is to sort the associative array by its keys in PHP.
There are different methods to sort Associative Array by keys, these are described below:
Table of Content
- Using ksort() Function
- Using uksort() Function
- Converting to a Regular Array for Sorting
Contact Us