Try this.. <?php $files = scandir('./images/'); $filter = array('', '.', '..'); $file = ''; while (in_array($file, $filter)) { $file = $files[array_rand($files, 1)]; } echo $file; // do whatever you want with this result. ?> PHP:
Here is the code for above link that I have sent http://www.hfolder.com/php_random_image/code.rar Have fun
I don't think there will be an infinite loop because because the resulting array of scandir will always have two entries - . and .. even if there are no files inside the directory. But that's only based on my observation.. Just to be safe.. here's a modified version. <?php $files = scandir('./images/'); $filter = array('', '.', '..'); $file = ''; if (count($files)>2) { while (in_array($file, $filter)) { $file = $files[array_rand($files, 1)]; } } echo $file; // do whatever you want with this result. ?> PHP:
How would it break out of the loop? Every time through, $file would be '', '.', or '..'. But yeah, the fixed version doesn't have this problem.