TP-Docs
HTML5 Icon HTML5 Icon HTML5 Icon
TP on Social Media

Recent

Welcome to TinyPortal. Please login or sign up.

March 29, 2024, 04:57:06 AM

Login with username, password and session length
Members
Stats
  • Total Posts: 195,105
  • Total Topics: 21,213
  • Online today: 304
  • Online ever: 3,540 (September 03, 2022, 01:38:54 AM)
Users Online
  • Users: 0
  • Guests: 302
  • Total: 302

Random/Rotate Image on Page Load?

Started by Xarcell, December 21, 2007, 03:51:08 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Xarcell

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.

Dragooon

#1
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....

Xarcell

Thanks Dragooon, i'll give it a try...

Xarcell

It seems to work, but sometimes doesn't load the image. I think it's a browser issue.

Dragooon

Maybe its coming to image which doesn't exists?

IchBin

Yes, if you don't have enough if/else statements to use all the images up to 10 it will not show one. :)

Xarcell

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.

jacortina

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)], '" />';

IchBin

What does the - 1 do in the count function for this?

jacortina

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).

Xarcell

I found my problem...

This retard didn't spell his file names right. :P

Dragooon