Scandir - sort numeric file names

Have done some searches but cannot find the exact answer I'm looking for.

I would like to take files with numbered file names using "scandir ($ dir)", but sort them correctly. For example, file names:

1-something.ext 2-something-else.ext 3-a-third-name.ext . . . 10-another-thing.ext 11-more-names.ext 

The problem I ran into is that the 10-a-fourth thing .ext will show before 2-something-else.ext. I would like to find a better way to solve this problem than typing "0" before all file names.

Any thoughts? Thanks.

+6
source share
3 answers

natsort does exactly what you need.

sort with SORT_NUMERIC will also work for file names that start with numbers, but it will be split if there are also names that do not have numbers in front (all names with a prefix other than a number will be sorted to a number with a prefix names and their order relative to each other will be random, not literal).

+9
source

You can use this view:

 sort($arr, SORT_NUMERIC); // asuming $arr is your array 
+1
source

If you want to reassign keys (which natsort doesn't), use usort () in combination with strnatcmp () or strnatcasecmp ():

 usort($arr, 'strnatcmp'); // Or 'strnatcasecmp' for case insensitive 
0
source

Source: https://habr.com/ru/post/910846/


All Articles