PHP natcasesort Function | Case-Insensitive Natural Order

PHP natcasesort is an inbuilt function in PHP. It sorts an array using natural order algorithm in a case-insensitive manner. The sorting is done in a way a normal human will sort the array. Also, it does not check for the type of value for comparison. For example, in string representation 40 is less than 8 in standard sorting algorithms as 4 comes before 8 lexicographically. However, in natural order 40 is greater than 8. In this article, we will discuss the PHP natcasesort Function. Also, we will discuss a few examples of using it.

Note: The function sorts the array in a case-insensitive manner. In order to sort the array in a case-sensitive manner, use the PHP natsort Function.

Syntax

natcasesort ($array)

Parameters

The PHP natcasesort Function expects only one parameter. The array which you need to sort using natural order algorithm is the input to the function.

Return Value

The PHP natcasesort Function returns a boolean true on success and false on failure. Also, it sorts the original input array while maintaining the original keys of the input array.

Example

Consider the following example differentiating the working of natsort and natcasesort function.

<?php
        $array = array('IMG0.txt', 'img12.txt', 'img10.txt', 'img2.txt', 'img1.txt', 'IMG3.txt');
        $originalArray = $array; 

        //Case Sensitive Sorting
        natsort($array);
        print_r($array);

        //Case Insensitive Sorting
        natcasesort($originalArray);
        print_r($originalArray);

?>

The natsort Function will sort the array in a case-sensitive manner. It distinguishes between lowercase and uppercase characters. However, the natcasesort function does not differentiate between lowercase and uppercase characters. The output of the script will be as follows:

OUTPUT:
//Natural Order Sorting in Case Sensitive Manner
Array
(
    [0] => IMG0.txt
    [5] => IMG3.txt
    [4] => img1.txt
    [3] => img2.txt
    [2] => img10.txt
    [1] => img12.txt
)

//Natural Order Sorting in Case Insensitive Manner
Array
(
    [0] => IMG0.txt
    [4] => img1.txt
    [3] => img2.txt
    [5] => IMG3.txt
    [2] => img10.txt
    [1] => img12.txt
)

According to a standard sorting algorithm in string representation, 13 is smaller than 3. This is because 1 comes before 3 lexicographically. However, a regular human will sort 3 before 13 and 10. Therefore, the function sorts the array using the nautral order algorithm. Also, notice that the function maintains the original key-value association of the input array.

Conclusion

In this article, we discussed the PHP natcasesort Function. Also, you can read more about it on the Official PHP Documentation. Additionally, you can also read about more PHP Array Functions on Concatly.

Spread the Knowledge

Leave a Reply

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