3

I came across this block of code which pulls images from a folder specified and outputs them with the img tag:

  <?php
            $url = "./images/";
            $handle = opendir ($url);
            while (false !== ($file = readdir($handle))) {
                if($file != "." && $file != ".." && $file != basename(__FILE__)) {
            echo '<a href="'.$url.$file.'" class="lightbox" title="'.$file.'"><img src="'.$url.$file.'" alt="" /></a><br />'; 
?>

This works great, but the only thing I am having issues with is the ordering of the images.

So, let's say in my images folder, I have these images:

2.jpg
b.jpg
a.jpg
1.jpg

How can I make it so that it lists the images in numeric and alphabetical order? I would like the numbered images to come first then the alphabets, so it would list the images like this:

1.jpg
2.jpg
a.jpg
b.jpg
double-beep
  • 5,031
  • 17
  • 33
  • 41
Kevin Jung
  • 2,973
  • 7
  • 32
  • 35

5 Answers5

4

What you need is a natural language sort.

use the php function natsort().. here..

<?php
$url = "./images/";
$temp_files = scandir($url);
natsort($temp_files);
foreach($temp_files as $file) 
{
    if($file != "." && $file != ".." && $file != basename(__FILE__)) 
    {
        echo '<a href="'.$url.$file.'" class="lightbox" title="'.$file.'"><img src="'.$url.$file.'" alt="" /></a><br />';  
    }
}
?>
Stewie
  • 3,103
  • 2
  • 24
  • 22
1

<?php
    $url = "./test/";
    $exclude = array('.', '..');
    $files = array_diff(scandir($url), $exclude);
    natsort($files);
    print_r(array_values($files));
?>

Output:

Array
(
    [0] => 1.jpg
    [1] => 2.jpg
    [2] => a.jpg
    [3] => b.jpg
)
drudge
  • 35,471
  • 7
  • 34
  • 45
0

Instead of immediately echo-ing them, you can add the links to an array. Then use sort($array) to place them in the right order, and echo them by going through each one in a foreach loop like: foreach($array as $image) { echo ... }.

For more info, see: http://php.net/manual/en/function.sort.php

tvkanters
  • 3,519
  • 4
  • 29
  • 45
  • 2
    Also to add to the original post, you might want to check out php.net when you're looking to do something like sorting. If you did that before coming here you probably wouldn't have needed to ask the question. – zamN Mar 29 '11 at 21:11
0

I would store the filenames in an array and then use sort() to order the array. There is no easier way to do it due to the fact that reddir only returns the filenames like so:

The filenames are returned in the order in which they are stored by the filesystem.

Prisoner
  • 27,391
  • 11
  • 73
  • 102
0

The scandir() and glob() functions can both return arrays of sorted directory contents, or you can continue to use opendir/readdir() to construct an array manually.

If the sort order (or lack thereof) is not what you prefer, then you can use any of the array sorting functions to manipulate the order however you like. I tend to like natcasesort().

salathe
  • 51,324
  • 12
  • 104
  • 132