Search code examples
phpsortingnatural-sort

Sort array of strings with leading numbers followed by non-numeric characters


I can get a sorted filename list with the following code:

$log_files = scandir(LLP_LOG_DIR);
$sorted = sort($log_files);

the filename format is X.log, where X is a progressive numeric value.

How can I solve the problem of getting

0.log
1.log
10.log
11.log
2.log
3.log

where the wanted result is

0.log
1.log
2.log
3.log
[..]
9.log
10.log
11.log
[..]

I can strip the ".log" string, sort them etc, but what is the most efficient way?


Solution

  • try natsort instead,

    natsort($log_files)