pr0cz
pr0cz

Reputation: 507

glob Images and sort by name not working above Number 10

I have a really simple code with a problem I can't solve:

    $dirname = "some/directory";
    $images = glob($dirname."*.{png,jpg,jpeg}", GLOB_BRACE);
    
    sort($images);
    
    foreach($images as $item){
        $title = explode('/', trim($item, '/'));
$fourth_segment = $title[3];
$title= str_replace([".jpg", ".jpeg", ".png"], "", $title[3]);
    echo '<h3>'.$title.'</h3><br /><img src="'.$item.'" style="width:500px;" /><br /><br />';
    }

This sorts my directory and posts its images in an sorted order on my webpage. Problem I have now is, that it is only working up to number 9.

My Directory:

How it is sorted and shown by my code on the webpage:

So its sorting as it should up to Number 9, but I don't get behind why the 10 is following the 1 and how I can solve this.

Does someone have an idea?

best regards

Upvotes: 0

Views: 114

Answers (1)

Ricardo Machado
Ricardo Machado

Reputation: 782

It seem the sort is being done in an Alphabetic way. In Alphabetic sort, it makes sense for the 10 to appear before 9. In the same way it makes sense to "BA" appears before "I" for words sorted alphabetic. (0 = A, 1 = B, I = 9).

According to the documentation, the sort funcion accepts a flag parameter to modify the sorting behaviour. You can try to use the sort function like this:

sort($images, SORT_NATURAL);

Upvotes: 1

Related Questions