␡
- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
3.14 Sorting Sensibly
You want to make your program sort a list like a human would, where the number 10 would come after the number 2.
Technique
Use the natsort() function:
<?php $files = array("file001.txt", "file002.txt", "file003.txt", "file010.txt", "file023.txt", "file004.txt"); natsort($files); foreach ($files as $file) { print "$file\n"; } ?>
Comments
The natsort() function uses a sorting algorithm that is described by Martin Pool at http://www.linuxcare.com.au/projects/natsort/. A case-insensitive version of the natsort() function is also available, natcasesort().