Hi,
the code again with some more comments on what exactly each line does 🙂
I modified the code a bit.
<?
// #### RANDOM PIC #########################################
// initialize the string containing the filenames
// to be empty at the beginning
$thumbstring = "";
// define an array containing all the paths we want
// to search (without the trailing slash)
$file_dirs = array("images1","images2","images3");
// we only want to select file that end with tn.jpg
$f_type = "tn.jpg"; // FILE EXTENSION YOU WISH TO DISPLAY
// get one of the directories (random)
// first we initialize the internal random number generator
srand ((float) microtime() * 10000000);
// then we want to select exactly one of the directories
// randomly
$key = array_rand($file_dirs, 1);
// if we choose to only select one field of the array randomly
// array_rand will give use the key, so we will have to select
// the directory by key
$file_dir = $file_dirs[$key];
// open the directory and get a handle to the directory
$dir=opendir($file_dir);
// loop through all entries in that directory
while ($file=readdir($dir))
{
// we will soon use the php function is_file in the next step
// the results are cached so we flush that cache to make sure
// that we get the correct result if the file has e.g. been
// deleted meanwhile
clearstatcache();
// check if the file is a regular file and not a directory
if (is_file($dir."/".$file))
{
// get the last six characters of the filename
$extension=substr($file,-6);
// check if it matches
if($extension == $f_type)
{
// match ... add the file to the string of files
$thumbstring .= "$file|";
}
}
}
// we have a | at the end of the string, that would cause
// explode to add an empty value at the end of our file array
$thumbstring = substr($thumbstring,0,-1);
// test if we found some files at all
if (strlen($thumbstring))
{
// create the array of filenames
$arry_txt = explode("|" , $thumbstring);
// select one of them randomly and print the img tag
echo "<img src=\"".$file_dir."/".$arry_txt[rand(0, sizeof($arry_txt) -1)]."\">";
}
// #### END RANDOM PIC #########################################
?>
While writing the comments I saw that the code isn't really optimal. If some of the directories are empty and some are not
and we get an empty directory at the first step we wouldn't
select a file at all. In that case we'd rather want to try another
directory to see if there is a file in it.
So I think that it would be better to use the other solution I mentioned -> fetch all files in all directories into an array and select one randomly. Another solution (if you have a huge amount of files) could be to first check if any of the directories are empty and to build a temporary array that only contains the directories not being empty selecting a directory randomly afterwards.
I hope that doesn't sound too confusing to you. I can give you an example for that if you wish.