Sorting Without Using uasort() in PHP

The uasort() function in PHP is used to sort an array while maintaining the association between keys and values. If you want to achieve custom sorting without using uasort(), you can implement a sorting algorithm like Selection Sort or Bubble Sort with a custom comparison function.

Method: Implementing Custom Sorting Without uasort()

We will manually write a sorting function where the order is decided based on a custom comparison logic. We will implement a Bubble Sort with a user-defined comparison function for sorting an associative array.

Code Example:

<?php
$array = [
    "apple" => 3,
    "orange" => 1,
    "banana" => 2,
    "grape" => 5,
];

// Custom comparison function for sorting in ascending order
function customCompare($a, $b) {
    return $a - $b;
}

// Bubble Sort with custom comparison function
$keys = array_keys($array);
$length = count($array);

for ($i = 0; $i < $length - 1; $i++) {
    for ($j = 0; $j < $length - $i - 1; $j++) {
        if (customCompare($array[$keys[$j]], $array[$keys[$j + 1]]) > 0) {
            // Swap the keys if the order is wrong
            $temp = $keys[$j];
            $keys[$j] = $keys[$j + 1];
            $keys[$j + 1] = $temp;
        }
    }
}

// Rebuild the sorted array
$sortedArray = [];
foreach ($keys as $key) {
    $sortedArray[$key] = $array[$key];
}

// Print sorted array
print_r($sortedArray);
?>

Output:

Array
(
    [orange] => 1
    [banana] => 2
    [apple] => 3
    [grape] => 5
)

Explanation:

  1. Custom Comparison Function: We defined a customCompare() function that compares two values and returns their difference, allowing us to sort the array values in ascending order.
  2. Bubble Sort with Custom Logic: The sorting is done by manually iterating through the array and swapping the values based on the custom comparison function.
  3. Rebuilding the Sorted Array: After sorting the keys, we rebuild the array in the sorted order by iterating through the keys.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *