Dynadot Aftermarket: discover domain gems worth investing in. Visit our aftermarket.

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
Close
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
Close
It worked, thanks heaps mate
 
0
Close
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
Close
DomainEasy: flexible LTO options. Close more domain deals with financing.

We're social

Escrow.com
Spaceship
Domain Recover
CryptoExchange.com

NamePros updates

Switch between accounts
You can now stay logged in to more than one NamePros account in the same browser. Click your avatar, then "Accounts in this browser", to...
AIVikings
Catchy
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back