tags:

views:

42

answers:

4

hi there, i wonder if there's a way of reading a directory in a random order.

With the following code i'm running through the directory thumbs and it's printing images on my website. However, they are always read alphabetically and i wonder if there's a way in doing this randomly?

<?php
$path = 'thumbs';
if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != '.' && $file != '..' && $file != '.DS_Store' && $file != 'Thumbs.db') {
                print "<img class='thumb' src='$path/$file'/>";

        } else {
            //no proper file
        }
    }
    closedir($handle);
}
?>

thank you for your suggestions!

regards

+3  A: 

why not put the results in an array and then randomly shuffling the array?

corroded
A: 

instead of printing the images put file names in an array, shuffle it when loop ends and make another loop after this for printing the values.

tazphoenix
A: 

Try with this function:

function getDirContent($dir='./'){
if ( is_dir($dir) ) {
    $fd = @opendir($dir);
    while ( ($part = @readdir($fd)) == TRUE ) {
        clearstatcache();
        $dir_array[] = $part;
    }
    if($fd == TRUE) {
        closedir($fd);
    }
    if (is_array($dir_array)) {
        shuffle($dir_array);
        return $dir_array;
    } else {
        Return FALSE;
    }
}

}

vucetica
A: 
$files = glob("$path/*.[JjGg][PpIi][GgFf]");
shuffle($files);
Col. Shrapnel