natsort Function Without Using Built-in Array Functions

Sorting arrays in PHP using natural order is often done with the natsort function. However, there may be situations where you want to replicate this functionality without relying on PHP’s built-in array functions. This article explains how to create your custom natsort-like function.

What Is natsort?

The natsort function in PHP sorts an array using a “natural order” algorithm, which means it organizes numeric strings based on their numerical value rather than lexicographically. For example:

$input = ["item10", "item2", "item1", "item20"];
natsort($input);
print_r($input);

Output:

Array
(
    [2] => item1
    [1] => item2
    [0] => item10
    [3] => item20
)

Custom Implementation of natsort

Let’s create a manual implementation of the natsort function.

function customNatSort(array $array): array {
    // Define a natural comparison function
    $compare = function ($a, $b) {
        // Use strnatcmp for natural comparison
        $pattern = '/(\d+)|(\D+)/'; // Separate numbers and non-numbers
        preg_match_all($pattern, $a, $matchesA, PREG_SET_ORDER);
        preg_match_all($pattern, $b, $matchesB, PREG_SET_ORDER);

        foreach ($matchesA as $index => $matchA) {
            $partA = $matchA[0];
            $partB = $matchesB[$index][0] ?? '';

            // Compare numbers as integers
            if (ctype_digit($partA) && ctype_digit($partB)) {
                $diff = (int)$partA - (int)$partB;
                if ($diff !== 0) return $diff;
            } else {
                // Compare non-numeric parts lexicographically
                $result = strcmp($partA, $partB);
                if ($result !== 0) return $result;
            }
        }

        // If one string has more parts, the shorter one comes first
        return count($matchesA) - count($matchesB);
    };

    // Use a simple sorting algorithm
    $length = count($array);
    for ($i = 0; $i < $length - 1; $i++) {
        for ($j = 0; $j < $length - $i - 1; $j++) {
            if ($compare($array[$j], $array[$j + 1]) > 0) {
                // Swap elements
                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;
            }
        }
    }

    return $array;
}

// Example usage
$input = ["item10", "item2", "item1", "item20"];
$sorted = customNatSort($input);

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

Output:

Array
(
    [0] => item1
    [1] => item2
    [2] => item10
    [3] => item20
)

Explain:

•  Understand Natural Order Sorting
Natural order sorting organizes items based on numerical values within strings. For example, "item10" comes after "item2".
•  Custom Implementation
The code provided demonstrates how to replicate the functionality using custom comparison logic.

Keep Learning 🙂

Leave a Reply

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