Dynadot .com transfer sale, only $10.12 with coupon code DYNA12, available while supplies last, ends October 1, 2026.

Help needed random image

Namecheap AuctionsNamecheap Auctions
SpaceshipSpaceship
SpaceshipSpaceship
Watch

zaros64

VIP Member
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.
GoDaddyGoDaddy
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
•••
Appraise.net

We're social

Escrow.com
Spaceship
Escrowly
CryptoExchange.com
Domain Recover
Catchy
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back