Custom Sorting Without Using usort() in PHP

The usort() function in PHP sorts an array by its values using a user-defined comparison function. If you want to sort an array without using usort(), you can manually implement a sorting algorithm like Bubble Sort or Selection Sort, incorporating a custom comparison function.

Method: Custom Sorting Without usort()

We will manually implement a sorting algorithm (e.g., Bubble Sort) with a custom comparison function to sort the array values.

Code Example:

<?php
$array = [3, 1, 5, 2, 4];

// Custom comparison function to sort in ascending order
function customCompare($a, $b) {
    return $a - $b;  // Ascending order
}

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

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

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

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Explanation:

  1. Custom Comparison Function: The customCompare() function compares two values. It returns a negative number if $a is less than $b, 0 if they are equal, and a positive number if $a is greater than $b. This ensures the sorting is in ascending order.
  2. Bubble Sort Algorithm: We use the Bubble Sort algorithm, which repeatedly compares and swaps adjacent elements based on the result of the custom comparison function.

Sorting Process: After sorting, the array values are arranged in ascending order.

Keep Learning 🙂

Leave a Reply

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