PHP natsort() Function

Example

Sort an array:

<?php
$temp_files = array("temp15.txt","temp10.txt",
"temp1.txt","temp22.txt","temp2.txt");
sort($temp_files);
echo "Standard sorting: ";
print_r($temp_files);
echo "<br>";
natsort($temp_files);
echo "Natural sorting: ";
print_r($temp_files);
?>

Running Instance

Definition and Usage

The natsort() function sorts the array using the 'natural sorting' algorithm. The keys retain their original key names.

In natural sorting algorithms, the number 2 is less than the number 10. In computer sorting algorithms, 10 is less than 2 because the first digit of '10' is less than 2.

Syntax

natsort(array)
Parameter Description
array Required. Specifies the array to be sorted.

The natsort() function sorts the elements of the given array using the natural order algorithm.

The natsort() function implements 'natural sorting', which is the sorting method for numbers from 1 to 9 and letters from a to z, with shorter ones taking precedence. The array indices are associated with the unit values.

If successful, the function returns TRUE, otherwise it returns FALSE.

Technical Details

Return Value: Returns TRUE on success, FALSE on failure.
PHP Version: 4+
Update Log: Starting from PHP 5.2.10, when 0 is used to fill a numeric string (e.g., '00006'), 0 will be ignored.