I have thousand directory folders like this: img/monkey-folder/ cute-monkey.jpg etc. etc img/turkey-folder/ img/rose-folder/ img/big-fish-folder/ img/more-folder/ etc. Each folder has 20 images. How to get only 1 random image? This code below is working but only pull 1 image from 1 folder. I need one random image from multiple folders. thanks <?php $imagesDir = 'img/monkey-folder/'; $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); $randomImage = $images[array_rand($images)]; echo $randomImage; //output img/monkey-folder/etc.jpg ?> Code (markup):
I think this could do that for you <?php $imagesDir = glob('img/*', GLOB_ONLYDIR); $randomfolder = $imagesDir[array_rand($imagesDir)]; $images = glob($randomfolder . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); $randomImage = $images[array_rand($images)]; echo $randomImage; //output img/monkey-folder/etc.jpg ?> Code (markup):
Thanks but still not working . Is it better to use glob or readdir? I want to display one image from many folders.
<?php $imagesDir = glob('img/*', GLOB_ONLYDIR); $randomfolder = $imagesDir[array_rand($imagesDir)]; $images = glob($randomfolder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE); $randomImage = $images[array_rand($images)]; echo $randomImage; //output img/monkey-folder/etc.jpg ?> Code (markup): try this, may be the missing / on line 4
This code does work, I have tested it. It was missing the slash. One thing I did notice, I have some images as .JPG not .jpg, and .PNG not .png. And so on. So you really may want to use this code instead. <style> .image { width:100px; height:100px; } </style> <?php $imagesDir = glob('Car/*', GLOB_ONLYDIR); $randomfolder = $imagesDir[array_rand($imagesDir)]; $images = glob($randomfolder . '/*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE); $randomImage = $images[array_rand($images)]; echo '<img src="'.$randomImage.'" class="image">'; ?> Code (markup):