Sort an array of file names with numbers?

Can someone tell me how to sort an array containing file names starting with numbers? Since the lines starting with 11, 12, 13, etc., are considered below 2, he cites my results as follows:

  [0] "1. File one.pdf"
 [1] "11. File eleven.pdf"
 [2] "12. File twelve.pdf"
 [3] "2. File two.pdf"
 [4] "3. File three.pdf"

Is there anything I can do to sort them correctly?

+6
string sorting arrays php numbers
source share
2 answers

You can use natsort . or natcasesort , which is case insensitive. If numbers are larger (e.g. diacritics), you should make sure to use locale .

If this is not enough, i.e. you also want to sort number literals ("one", "two", "three"), you can use usort , which allows you to use your own callback as a comparison function.

+6
source share

Usage can get natural order using natsort

Take a look.

+1
source share

All Articles