10

Done some searching, but can't seem to find the exact answer I'm looking for.

I'd like to pull in files with numbered filenames using 'scandir($dir)', but have them sort properly. For example, file names are:

1-something.ext

2-something-else.ext

3-a-third-name.ext

.

.

.

10-another-thing.ext

11-more-names.ext

The problem I'm having is that 10-a-fourth-thing.ext will show before 2-something-else.ext. I'd like to find a better way of solving this issue than introducing leading '0' in front of all file names.

Any thoughts? Thanks.

Phil
  • 1,849
  • 4
  • 24
  • 38
  • [How to sort an array of numeric strings which also contain numbers. (natural ordering) in PHP](https://stackoverflow.com/q/28363762/2943403) and [Sorting an array of directory filenames in descending natural order](https://stackoverflow.com/q/7377015/2943403) and [Sort an array of strings starting by numbers](https://stackoverflow.com/q/63357754/2943403) and [How do I sort alphabetically with pictures in php?](https://stackoverflow.com/q/47137436/2943403) – mickmackusa Feb 27 '23 at 02:29

3 Answers3

16

natsort does exactly what you need.

sort with SORT_NUMERIC will also work for filenames that start with numbers, but it will break if there are also names that have no numbers in front (all non-number-prefixed names will be sorted before number-prefixed names, and their order relative to one another will be random instead of alphabetic).

Jon
  • 428,835
  • 81
  • 738
  • 806
3

You can use sort like this:

sort($arr, SORT_NUMERIC); // asuming $arr is your array
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • That was my first impulse as well, but there are serious issues with it. – Jon Mar 15 '12 at 20:45
  • From the OP `I'd like to pull in files with numbered filenames` it appears that file names always have numbers in front. However if there are mixed ones then natsort is the way to go. – anubhava Mar 15 '12 at 20:49
1

If you want to reassign keys (which natsort does not do), use usort() combined with strnatcmp() or strnatcasecmp():

usort($arr, 'strnatcmp'); // Or 'strnatcasecmp' for case insensitive
RussSchick
  • 445
  • 3
  • 11