Home >>PHP Array Functions >PHP natsort() Function

PHP natsort() Function

PHP natsort() Function

PHP natsort() function is used to sort any given input array by using a "natural order" algorithm. It is case sensitive. It accepts only a single parameter $array that is the given input array. It returns a boolean value TRUE on success and FALSE on failure.

Syntax:

natsort($array);

Parameter Values

Parameter Description
array This is a required parameter. It defines the array to sort.

Here is an example of natsort() function in PHP:

<html>
<body>
<pre>
<?php
$x = array("a15","A10","a1","A22","a2");
natsort($x);
echo "Natural order case sensitve: ";
print_r($x);
?>
</pre>
</body>
</html>
Output:
Natural order case sensitve: Array
(
    [1] => A10
    [3] => A22
    [2] => a1
    [4] => a2
    [0] => a15
)

Example 2:

<html>
<body>
<pre>
<?php
$x = array("b15","A10","a1","B22","a2","c0","a50","A100");
natsort($x);
echo "Natural order case sensitve: ";
print_r($x);
echo "<br />";
natcasesort($x);
echo "Natural order case insensitve: ";
print_r($x);
?>
</pre>
</body>
</html>
Output:
Natural order case sensitve: Array
(
    [1] => A10
    [7] => A100
    [3] => B22
    [2] => a1
    [4] => a2
    [6] => a50
    [0] => b15
    [5] => c0
)

Natural order case insensitve: Array
(
    [2] => a1
    [4] => a2
    [1] => A10
    [6] => a50
    [7] => A100
    [0] => b15
    [3] => B22
    [5] => c0
)

No Sidebar ads