0

I have a bit of PHP code that grabs a list of files from a directory, and puts them into an array.

I can sort the array alphabetically, and the file list comes out like this:

(Ex A)

CC 2010.pdf
CCP 2010.PDF
RS 1 2010.PDF
RS 15 2010.PDF
RS 2 2010.PDF

I want PHP to sort alphabetically but also take into consideration sorting files with numeric components correctly, such as:

(Ex B)

CC 2010.pdf
CCP 2010.PDF
RS 1 2010.PDF
RS 2 2010.PDF
RS 15 2010.PDF

I do not know what type of sort this is called, but I do notice that Windows sorts files by the first list (A), and that Macs sort files by the more advanced/smarter bottom list (B)

I want to avoid having to add 0's to force the correct sorting order:

(Ex C)

CC 2010.pdf
CCP 2010.PDF
RS 01 2010.PDF
RS 02 2010.PDF
RS 15 2010.PDF

Does anyone know how I can get PHP to sort my array in the logical fashion of example (B)?

1 Answer 1

3

Either use natsort(), or if that doesn't fit, define your own logic in a function and use usort(). The term is 'natural sorting'.

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

Comments

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.