PHP Function Reference

PHP natsort() Function



The PHP natsort() function is used to sort an array according to the value and maintaining key to value association. This function implements a sort algorithm which uses "natural ordering" and sorts alphanumerically.

Syntax

natsort(array)

Parameters

array Required. Specify the input array.

Return Value

Returns true on success and false in failure.

Exceptions

NA.

Example:

In the example below, natsort() function is used to sort an array alphanumerically.

<?php
$Arr = array("Red"=>"Color1",
             "Green"=>"Color2",
             "Blue"=>"Color3",
             "White"=>"Color20");
   
asort($Arr);
echo "Standard sorting\n";
print_r($Arr);  

natsort($Arr);
echo "\nNatural order sorting\n";
print_r($Arr);
?>

The output of the above code will be:

Standard sorting
Array
(
    [Red] => Color1
    [Green] => Color2
    [White] => Color20
    [Blue] => Color3
)

Natural order sorting
Array
(
    [Red] => Color1
    [Green] => Color2
    [Blue] => Color3
    [White] => Color20
)

Example:

Consider one more example where this function is used to sort an indexed array alphanumerically.

<?php
$Arr = array("Color1", "Color2", "Color3", 
             "Color20", "Color15", "Color25");
   
asort($Arr);
echo "Standard sorting\n";
print_r($Arr);  

natsort($Arr);
echo "\nNatural order sorting\n";
print_r($Arr);
?>

The output of the above code will be:

Standard sorting
Array
(
    [0] => Color1
    [4] => Color15
    [1] => Color2
    [3] => Color20
    [5] => Color25
    [2] => Color3
)

Natural order sorting
Array
(
    [0] => Color1
    [1] => Color2
    [2] => Color3
    [4] => Color15
    [3] => Color20
    [5] => Color25
)

❮ PHP Array Reference