Custom Key Sorting Without Using uksort() in PHP
The uksort() function in PHP sorts an array by its keys using a user-defined comparison function. If you want to implement the same functionality manually without using uksort(), you can use a sorting algorithm like Bubble Sort or Selection Sort on the array’s keys.
Method: Custom Sorting by Keys Without uksort()
We will manually sort the keys of an associative array using a Bubble Sort algorithm with a custom comparison function.
Code Example:
<?php
$array = [
"apple" => 3,
"orange" => 1,
"banana" => 2,
"grape" => 5,
];
// Custom comparison function for keys (sorting alphabetically)
function customKeyCompare($a, $b) {
return strcmp($a, $b); // Compare keys as strings
}
// Bubble Sort with custom key comparison function
$keys = array_keys($array);
$length = count($keys);
for ($i = 0; $i < $length - 1; $i++) {
for ($j = 0; $j < $length - $i - 1; $j++) {
if (customKeyCompare($keys[$j], $keys[$j + 1]) > 0) {
// Swap the keys if they are not in order
$temp = $keys[$j];
$keys[$j] = $keys[$j + 1];
$keys[$j + 1] = $temp;
}
}
}
// Rebuild the sorted array based on the sorted keys
$sortedArray = [];
foreach ($keys as $key) {
$sortedArray[$key] = $array[$key];
}
// Print sorted array by keys
print_r($sortedArray);
?>
Output:
Array
(
[apple] => 3
[banana] => 2
[grape] => 5
[orange] => 1
)
Explanation:
- Custom Key Comparison: The
customKeyCompare()
function usesstrcmp()
to compare the keys of the array lexicographically (alphabetically). - Bubble Sort with Custom Key Comparison: We apply a Bubble Sort algorithm to sort the array’s keys based on our custom comparison function.
- Rebuilding the Array: After sorting the keys, we rebuild the array in the sorted key order by iterating through the sorted keys and assigning the corresponding values.
Keep Learning 🙂