TinyPortal

Development => Resources => Topic started by: Xarcell on December 21, 2007, 03:51:08 AM

Title: Random/Rotate Image on Page Load?
Post by: Xarcell on December 21, 2007, 03:51:08 AM
With PHP and not css, is there a simple way to rotate or show random image a on page load/refresh?

Trying to find something for my next theme project. I try to stay way from java.
Title: Re: Random/Rotate Image on Page Load?
Post by: Dragooon on December 21, 2007, 03:58:13 AM
You can use the rand() function
Something like
$image = rand(0,10);
if($image == 1)
echo '<img src="1" />';
elseif($image == 2)
echo '<img src="2" />';
elseif($image == 3)
echo '<img src="3" />';

And so on....
Title: Re: Random/Rotate Image on Page Load?
Post by: Xarcell on December 21, 2007, 02:48:17 PM
Thanks Dragooon, i'll give it a try...
Title: Re: Random/Rotate Image on Page Load?
Post by: Xarcell on December 21, 2007, 11:45:54 PM
It seems to work, but sometimes doesn't load the image. I think it's a browser issue.
Title: Re: Random/Rotate Image on Page Load?
Post by: Dragooon on December 22, 2007, 02:09:17 AM
Maybe its coming to image which doesn't exists?
Title: Re: Random/Rotate Image on Page Load?
Post by: IchBin on December 22, 2007, 02:58:33 AM
Yes, if you don't have enough if/else statements to use all the images up to 10 it will not show one. :)
Title: Re: Random/Rotate Image on Page Load?
Post by: Xarcell on December 22, 2007, 03:32:36 AM
Quote from: IchBinâ,,¢ on December 22, 2007, 02:58:33 AM
Yes, if you don't have enough if/else statements to use all the images up to 10 it will not show one. :)

Yeah, I changed it to 4, because I had 4 images.
Title: Re: Random/Rotate Image on Page Load?
Post by: jacortina on December 22, 2007, 03:33:43 AM
You might want to put the pic filenames into an array and then use the count as your rand() limit. Also, as written, 0 (zero) is a possible result (rand() is inclusive of the arguments used for range).

$pics = array('abc.gif', 'def.jpg', 'ghi.png');
echo '<img src="http://yourdomain/path-to-images/', $pics[rand(0,count($pics) - 1)], '" />';
Title: Re: Random/Rotate Image on Page Load?
Post by: IchBin on December 22, 2007, 03:41:07 AM
What does the - 1 do in the count function for this?
Title: Re: Random/Rotate Image on Page Load?
Post by: jacortina on December 22, 2007, 03:43:57 AM
The array index will go from 0 to 3 if you have 4 array members. Count will equal 4, so you need to subtract 1 from it to make it rand(0,3). (it's not in the count function itself; it's subtracting 1 from the count result).
Title: Re: Random/Rotate Image on Page Load?
Post by: Xarcell on December 22, 2007, 05:38:52 AM
I found my problem...

This retard didn't spell his file names right. :P
Title: Re: Random/Rotate Image on Page Load?
Post by: Dragooon on December 22, 2007, 05:50:51 AM
LOL!
This happens to me many times.