| re: Choose random image from dir and display it
kingofkolt wrote:[color=blue]
> I have a directory of images, called "random". In it are the following
> files:
>
> 1.gif
> 2.gif
> 3.gif
> 4.gif
>
> I use this script to choose a random image and display it:
>
> $i = -2; // $i = -2 so that the directory files ("." and "..") won't be
> counted.
> if ( $dh = opendir( "images/random" ) ) {
> while ( false !== ( $file = readdir( $dh ) ) ) {
> $i++;
> }
> closedir( $dh );
> $rand = rand( 1, $i );
> $randimg = '<img src="images/random/' . $rand . '.gif" />';
> }
> print $randimg;
>
> This works just dandy. However, I figure there must be a more efficient way
> to count the number of files in a directory. Is there a directory's
> equivalent of a function like file()? Or is my script the only way to count
> the files?
>
> Thanks.
> - JP
>
>[/color]
php 4.3 or greater:
$imgGroup = glob("images/random/{*.jpg,*.gif,*.png}", GLOB_BRACE);
echo "
<img src = {$imgGroup[rand(0, count($imgGroup)-1)]} />
";
Fox
************** |