php random pic

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dsjoes
Forum Commoner
Posts: 41
Joined: Thu May 20, 2010 3:15 pm

php random pic

Post 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>
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: php random pic

Post 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] . '" />';
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply