Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - sorting an array of filenames with numbers?

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?

like image 826
Tim Avatar asked Dec 30 '10 08:12

Tim


People also ask

How do you sort an array of objects in PHP?

Approach: The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.

How do you sort names in a file?

To sort files in a different order, click the view options button in the toolbar and choose By Name, By Size, By Type, By Modification Date, or By Access Date. As an example, if you select By Name, the files will be sorted by their names, in alphabetical order. See Ways of sorting files for other options.

How do I sort descending in PHP?

The krsort() function sorts an associative array in descending order, according to the key. Tip: Use the ksort() function to sort an associative array in ascending order, according to the key. Tip: Use the arsort() function to sort an associative array in descending order, according to the value.


2 Answers

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.

like image 190
ts. Avatar answered Oct 20 '22 21:10

ts.


Use can get the natural ordering using natsort

See it.

like image 30
codaddict Avatar answered Oct 20 '22 22:10

codaddict