2

There are many similar questions and I almost have the solution but I have a case that isn't sorted like the client wants it.

I am using the following function to sort my array:

function sortFilesByName($a, $b) {
    if (basename(strtolower($a['path'])) == basename(strtolower($b['path']))) {
        return 0;
    }
    return (basename(strtolower($a['path'])) < basename(strtolower($b['path']))) ? -1 : 1;
}

The problem is that I get the following order when sorting my list:

  1. file2.png
  2. file3.png
  3. file4.png
  4. file5.png
  5. file6.png
  6. file7.png
  7. file8.png
  8. file9.png
  9. file10.png
  10. file11.png
  11. file1.png

The client would like to have file1.png at the top of the list and I have to say I'm a little confused as how to achieve that. Any help is appreciated :)

After the answers given I've gotten much closer, I changed my function to the following:

function sortFilesByName($a, $b) {
    return strnatcmp(strtolower(basename($a['path'])), strtolower(basename($b['path'])));
}

And it works! Thanks!

2 Answers 2

3

I think you need the natsort(); function instead. It sorts alphanumerically.

<?php 
   $numbers = array("1.gif","2.gif","20.gif","10.gif"); 
   natsort($numbers); 
   print_r($numbers); 
?> 

Outputs

Array
(
[0] => 1.gif
[1] => 2.gif
[3] => 10.gif
[2] => 20.gif
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, your answer lead me to right spot, posted my new function in my question.
3

The natsort function will do what you want: http://php.net/manual/en/function.natsort.php.

1 Comment

Thanks, natsort uses the algorithm that I needed which lead me to natsortcmp!

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.