w3resource

PHP: natsort() function

PHP: Sort an array using a 'natural order' algorithm

The natsort() function is used to sorts an array using a "natural order" algorithm. The function implements a sort algorithm but maintains original keys/values.

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations.

Version:

(PHP 4 and above)

Syntax:

natsort(array_name)

Parameter:

Name Description Required /
Optional
Type
array_name The input array. Required Array

Return value:

TRUE on success or FALSE on failure.

Value Type: Boolean.

Example:

<?php
$php_files = array("code12.php", "code22.php",
"code2.php", "code3.php", "code1.php");
natsort($php_files);
echo "List of file using natural order: ";
print_r($php_files);
?>

Output:

List of file using natural order: Array ( [4] => code1.php [2] => code2.php [3] => code3.php [0] => code12.php [1] => code22.php )

Pictorial Presentation:

php function reference: natsort() function

View the example in the browser

Practice here online:

See also

PHP Function Reference

Previous: natcasesort
Next: next



Follow us on Facebook and Twitter for latest update.