Dynadot โ€” .com Registration $8.99

Help needed random image

Spaceship Spaceship
Watch
Impact
34
Sorry if this seems like a stupid question. I'm a beginner and I'm not sure what to do
I have 5 images from 1-4.png and 5.jpg (5 images in total, 4 pngs and 1 jpg)
I want to show a random image so I generate a number from 1-5 using
PHP:
$random=rand(1,5)
this is where I'm stuck
PHP:
if (file_exists($random)) {

How do I add the .jpg or .png file extension after $random without it creating an error
basically I want it to do this

if random.png exists echo random.png else echo random.jpg

thanks and I hope you understand me
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
AfternicAfternic
If its just a simple image rotator you want to drop into your script this should do:

PHP:
$random=rand(1,5);
if (file_exists($random.'.png')) {
echo "<img src='$random.png' alt='' />";
} elseif(file_exists($random.'.jpg')) {
echo "<img src='$random.jpg' alt='' />";
}

(Haven't tested it, let me know if it works!)
 
Last edited:
0
•••
It worked, thanks heaps mate
 
0
•••
Also, if you didn't want to rename your files to numbers, you could use a switch statement:

PHP:
$random = rand(1, 5);
switch($random) {
case 1:
echo "image1.jpg";
break;
case 2:
echo "image2.png";
break;
case 3:
echo "image3.png";
break;
case 4:
echo "image4.png";
break;
case 5:
echo "image5.png";
break;
}
 
0
•••
Unstoppable Domains
Domain Recover
NameMaxi - Your Domain Has Buyers
  • The sidebar remains visible by scrolling at a speed relative to the pageโ€™s height.
Back