This function simply sorts an array in ascending order by element value, keeping key/value relationships intact. However, the algorithm sorts the values as strings according to the rules typically used by humans to order alphanumeric strings. This gives a very natural result.
The basic idea is that any strings of digits embedded within the strings being sorted are compared according to their actual numeric values, and not according to the character codes of the individual digits. For instance, while in a normal computer sort the value b2 would be considered to be greater than b10 (since 1 comes before 2), a natural sorting algorithm looks at the values of the embedded numbers - in this case, 2 and 10 - and places b2 first.
This function also handles multiple numeric sequences within the same string and separated by non-digit characters.
See also array_multisort() , arsort() , asort() , krsort() , natcasesort() , ksort() , rsort() , sort() , uasort() , uksort() , usort()
Example 52. Sort in natural order
$normal = $natural = array('b2', 'b10', 'a12', 'a7'); sort($normal); echo "Normal sort using sort():\n"; print_r($normal); $array = array('b2', 'b10', 'a12', 'a7'); natsort($natural); echo "Natural sort using natsort():\n"; print_r($natural); Output: Normal sort using sort(): Array (  => a12  => a7  => b10  => b2 ) Natural sort using natsort(): Array (  => a7  => a12  => b2  => b10 )
PHP Functions Essential Reference. Copyright © 2002 by New Riders Publishing (Authors: Zak Greant, Graeme Merrall, Torben Wilson, Brett Michlitsch). This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/). The authors of this book have elected not to choose any options under the OPL. This online book was obtained from http://www.fooassociates.com/phpfer/ and is designed to provide information about the PHP programming language, focusing on PHP version 4.0.4 for the most part. The information is provided on an as-is basis, and no warranty or fitness is implied. All persons and entities shall have neither liability nor responsibility to any person or entity with respect to any loss or damage arising from the information contained in this book.