PHP natsort is an inbuilt function in PHP. It sorts an array using natural order algorithm which is how a normal human being would sort the array. Therefore, 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 natsort Function. Also, we will discuss a few examples of using it.
Note: The function sorts the array in a case-sensitive manner. In order to sort the array in case-insensitive manner, use the PHP natcasesort Function.
The PHP natsort Function expects only one parameter. The array which you need to sort using natural order algorithm is the input to the function.
The PHP natsort 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.
Let’s discuss a few examples of using the function.
Example 1: Simple Sorting
For instance, consider a list of file names to be sorted as follows:
<?php $array = array("13.txt", "10.txt", "3.txt", "1.txt"); $originalArray = $array; //Standard Sorting Algorithm sort($array); print_r($array); //Natural Order Sorting natsort($originalArray); print_r($originalArray); ?>
In the above example, first we sort the array using standard PHP sort Function. Then, we sort the same array using Natural Order Algorithm. Notice the difference between the outputs:
OUTPUT: //Standard Sorting Algorithm Array (  => 1.txt  => 10.txt  => 13.txt  => 3.txt ) //Natural Order Algorithm Array (  => 1.txt  => 3.txt  => 10.txt  => 13.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 nautral order algorithm. Also, notice that the function maintains the original key-value association of the input array.
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.