natcasesort Function Without Using Built-in Array Functions

In this post, we’ll recreate the functionality of PHP’s natcasesort without relying on the built-in array functions. This custom function will allow you to perform a natural case-insensitive sort on an array.

What Is natcasesort?

The natcasesort function in PHP sorts an array using a “natural order” algorithm, ignoring case sensitivity. For example:

$input = ["file10", "File2", "file1", "file20"];
natcasesort($input);
print_r($input);

Output:

Array
(
    [2] => file1
    [1] => File2
    [0] => file10
    [3] => file20
)

Custom Implementation of natcasesort

Let’s implement this functionality manually

function customNatCaseSort(array $array): array {
    // Convert all elements to lowercase for case-insensitive comparison
    $lowercaseArray = array_map('strtolower', $array);
    
    // Use a custom comparison function
    usort($array, function ($a, $b) use ($lowercaseArray) {
        // Natural order comparison for lowercase values
        return strnatcmp(strtolower($a), strtolower($b));
    });
    
    return $array;
}

// Example usage
$input = ["file10", "File2", "file1", "file20"];
$sorted = customNatCaseSort($input);

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

Output:

Array
(
    [0] => file1
    [1] => File2
    [2] => file10
    [3] => file20
)

Keep Learning 🙂

Leave a Reply

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