Re: Choose random image from dir and display it
From: Fox (fox_at_fxmahoney.com)
Date: 10/30/04
- Previous message: Theo: "Re: Choose random image from dir and display it"
- In reply to: kingofkolt: "Choose random image from dir and display it"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 30 Oct 2004 00:59:54 -0500
kingofkolt wrote:
> 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
>
>
php 4.3 or greater:
$imgGroup = glob("images/random/{*.jpg,*.gif,*.png}", GLOB_BRACE);
echo "
<img src = {$imgGroup[rand(0, count($imgGroup)-1)]} />
";
Fox
**************
- Previous message: Theo: "Re: Choose random image from dir and display it"
- In reply to: kingofkolt: "Choose random image from dir and display it"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|