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.
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.
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.
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 (  => IMG0.txt  => IMG3.txt  => img1.txt  => img2.txt  => img10.txt  => img12.txt ) //Natural Order Sorting in Case Insensitive Manner Array (  => IMG0.txt  => img1.txt  => img2.txt  => IMG3.txt  => img10.txt  => 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.
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.
Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.