tags:

views:

128

answers:

4

i have one directory called imaages/tips

Now in that i have many images which can chnage

I want that the php script should read the directory , finds the images and out of those images found pick random image very time

Any idea

+3  A: 
$images = glob('images/tips/*');
return $images[rand(0, count($images) - 1)];

However, this doesn't ensure that the same image isn't picked twice consecutively.

Ignas R
Adding that insurance would detract from the randomness. It also might introduce bugs.
wallyk
I had no clue that glob() function existed. Nice.
keithjgrant
A: 

You can use opendir() to read in the filenames from that directory, storing each filename in an array. Then use rand() with a min and max corresponding to your array keys to select an item from the array.

keithjgrant
A: 

Hi,

Load folder with images:

$folder = opendir(images/tips/);

Build table out of files/images from directory:

$i = 0;
while(false !=($file = readdir($folder))){
if($file != "." && $file != ".."){
    $images[$i]= $file;
    $i++;
    }
}

Pick random:

$random_img=rand(0,count($images)-1);

Show on page:

echo '<img src="images/tips'.$images[$random_img].'" alt="" />';

Hope it helps. Of course enclose it in <?php ?>.

BR, Dawid.

Czlowiekwidmo
Two issues. Don't you need another slash after `tips`?And why not just do `$images[] = $file` and forget the counter?
Mark
+7  A: 
$imagesDir = 'images/tips/';

$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$randomImage = $images[array_rand($images)]; // See comments

You can send a 2nd argument to array_rand() to get more than 1.

It looks like some people don't know array_rand() exists.

alex
Actually, you'd have to do$randomImage=$images[array_rand($images)];From the manual:"array_rand() returns the key for a random entry."
Alex JL
thank buddy , that worked perfectlyThis webiste is great for getting help.Is there any option that when some comment is posted or answers is given i get email because i had three answers and i didn't get email , i ticked the notify box but still could not get email
Mirage
@Mirror51 Bring up the issue on meta.stackoverflow.com
alex