Javatpoint Logo
Javatpoint Logo

PHP natsort() function

The PHP natsort( ) function is used to sort an array using a "natural order" algorithm. The natsort( ) function implements a sort algorithm but maintains original keys and values. This function was introduced in PHP 4.0.

Syntax

Parameter

Parameter Description Is compulsory
array Specifies the array to sort. compulsory

Returns

The natsort( ) function returns true on success or false on failure.

Example 1

Output:

Standard sorting: Array
(
    [0] => Ruby
    [1] => html
    [2] => java 8
    [3] =>php 5
    [4] => python
)
Natural order: Array
(
    [0] => Ruby
    [1] => html
    [2] => java 8
    [3] =>php 5
    [4] => python
)

Example 2

Output:

Standard sorting
Array
(
    [0] => code1.php
    [1] => code12.php
    [2] => code2.php
    [3] => code22.php
    [4] => code3.php
)

Natural order sorting
Array
(
    [4] => code1.php
    [2] => code2.php
    [3] => code3.php
    [0] => code12.php
    [1] => code22.php
)

Example 3

Output:

Standard sorting
Array
(
    [0] => android7
    [1] => java8
    [2] => php5
    [3] => python3
    [4] => ruby2
)
Natural order sorting
Array
(
    [4] => android7
    [0] => java8
    [1] => php5
    [2] => python3
    [3] => ruby2
)

Example 4

Output:

Standard sorting
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)
Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)





Help Others, Please Share

facebook twitter pinterest