Page 1 of 1

php random pic

Posted: Mon Mar 07, 2011 4:01 pm
by dsjoes
i have got this script which displays all folders within a folder but what i want to do now is get it to display a random picture for each of the folders that it is showing in the grid.

script

Code: Select all

<form name="Gallery" method="post">
<?php
$path = "gallery_files/gallery/";
$dir_handle = @opendir($path) or die("Unable to open folder");
 
echo "<table cellspacing='15'>";
echo "<tr>";
while (false !== ($folder = readdir($dir_handle))) {
if($folder == "index.php")
continue;
if($folder == ".")
continue;
if($folder == "..")
continue;

echo ($x % 6 == 0) ? "</tr><tr>" : "";
echo "<td><a href='pictures/?folder=$folder'><img src='path/to/random/image' style='height:auto;width:110px;' alt='$folder'></a><br /><a href='pictures/?folder=$folder'>$folder</a></td>";
  $x++;
}
echo "</tr>";
echo "</table>";
closedir($dir_handle);
?>
</form>

Re: php random pic

Posted: Tue Mar 08, 2011 10:39 am
by social_experiment
Create an array that contains image names and use array_rand() to select a random image. array_rand returns the key of the element that is chosen if only 1 'random' element is needed. $random_image will contain either (in this case) 0, 1, 2.

Code: Select all

<?php
 $image_array = array('a.jpg', 'b.jpg', 'c.jpg');
 $random_image = array_rand($image_array);
 // $image_array[$random_image] where $random_image is the key
 echo '<img src="/path/to/file/' . $image_array[$random_image] . '" />';
?>