0

i am reading all the files from folder dataand i want to sort them.

$dir = 'data';
$all_files = glob($dir.'/*.*');
asort($all_files);

foreach($all_files as $file) {  
    echo $file.'<br />';
}

Code above gives me as output:

data/1.txt
data/10.txt
data/11.txt
data/2.txt
data/3.txt
...

How can i sort them so that the output will be:

data/1.txt
data/2.txt
data/3.txt
...
data/10.txt
data/11.txt
1
  • 1
    The time traveller's solution would be to consider the largest conceivable number that could be in the filename, and then zero-pad to at least one additional digit. Eg: sprintf("foo_%06d.txt", 42); // foo_000042.txt Commented Jan 13, 2020 at 21:08

2 Answers 2

2

strnatcmp

usort($all_files, "strnatcmp");
print_r($all_files);

Or


sort($all_files, SORT_NATURAL | SORT_FLAG_CASE);

Or

natsort


natsort($all_files);

Sign up to request clarification or add additional context in comments.

Comments

2

Add the sorting rule to your asort line:

asort($all_files, SORT_NATURAL);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.