8

Can anyone tell me how to sort an array containing filenames that start with numbers? Because strings that start with 11, 12, 13 etc are considered lower than 2, it's scewing my results like this:

[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 these properly?

2 Answers 2

8

You can use natsort. or natcasesort, which is case insensitive. If there is more than numbers (ie. diacritics), you should assure that you use proper locale.

If it is not enough, ie. you want also sort number literals ("one", "two", "three"), you can use usort, which permits to use your custom callback as comparison function.

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

1 Comment

Perfect! Thank you, and everyone else who put in an answer.
2

Use can get the natural ordering using natsort

See it.

1 Comment

What was the link supposed to be? It's dead now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.