0

I have a number of files I am loading into a slideshow, I have them numbered by the client in the order that they'd like to be displayed.

I'm grabbing them with glob $pics = glob("images/slideshow/*.jpg", GLOB_NOSORT); but for some reason I'm getting the old Windows sorting bug, of 11 being sorted above 2.

For example,

Array
(
    [0] => images/slideshow/1.jpg
    [1] => images/slideshow/14.jpg
    [2] => images/slideshow/15.jpg
    [3] => images/slideshow/16.jpg
    [4] => images/slideshow/18.jpg
    [5] => images/slideshow/2.jpg
    [6] => images/slideshow/20.jpg
    [7] => images/slideshow/21.jpg
    [8] => images/slideshow/22.jpg
    [9] => images/slideshow/23.jpg
    [10] => images/slideshow/24a.jpg
    [11] => images/slideshow/25.jpg
    [12] => images/slideshow/26.jpg
    [13] => images/slideshow/29.jpg
    [14] => images/slideshow/3.jpg
    [15] => images/slideshow/36.jpg
    [16] => images/slideshow/38.jpg
    [17] => images/slideshow/4.jpg
    [18] => images/slideshow/40.jpg
    [19] => images/slideshow/41.jpg
    [20] => images/slideshow/5.jpg
    [21] => images/slideshow/6.jpg
    [22] => images/slideshow/7.jpg
)

I've run it through asort() and I can't seem to find out why this isn't working, short of it being something about them being strings, rather than strictly numbers.

5
  • it's not a bug, php would treat your path as string as it's supposed to do, you need to tell it specifically to sort based on the filename Commented Mar 21, 2012 at 18:21
  • Windows used to do this, I didn't mean PHP :) Commented Mar 21, 2012 at 18:26
  • possible duplicate of Php filename sorting Commented Mar 21, 2012 at 18:41
  • @DavidYell please search SO (and ideally elsewhere) for answers before posting a question. Commented Mar 21, 2012 at 18:42
  • @salathe I did search, in the PHP tag for this, but after two attempts at different wording, I couldn't find an answer which worked. Apologies. Commented Mar 22, 2012 at 16:53

1 Answer 1

6

Check out natsort:

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations.

$array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

print_r($array2);

Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)
Sign up to request clarification or add additional context in comments.

1 Comment

Genius, I've not seen that function before. Thanks!

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.