PHP natsort Function | Sort Using Natural Order Algorithm

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.

Syntax

natsort ($array)

Parameters

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.

Return Value

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.

Examples

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
(
    [0] => 1.txt
    [1] => 10.txt
    [2] => 13.txt
    [3] => 3.txt
)

//Natural Order Algorithm
Array
(
    [3] => 1.txt
    [2] => 3.txt
    [1] => 10.txt
    [0] => 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.

Conclusion

In this article, we discussed the PHP natsort 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 *