natsort()
natsort() — Sort an array using a "natural order" algorithm.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort()) can be seen in the example below.
Signature
natsort(array &$array): true
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| &$array | array | The input array. |
Return value
Always returns true.
Example
A runnable snippet:
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png"); asort($array1); echo "Standard sorting\n"; print_r($array1); natsort($array2); echo "\nNatural order sorting\n"; print_r($array2);
Output:
Standard sorting Array ( [3] => img1.png [1] => img10.png [0] => img12.png [2] => img2.png ) Natural order sorting Array ( [3] => img1.png [2] => img2.png [1] => img10.png [0] => img12.png )
Changelog
| Version | Change |
|---|---|
| 8.2.0 | The return type is true now; previously, it was bool. |
See also
natcasesort(), strnatcmp(), strnatcasecmp()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page natsort() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.