Reputation: 555
OK, so I have a site I'm working on and need two images displayed on the page that are random. I'm running XAMPP to test it locally before it goes live. The image bank is stored in an 'images' folder in the root. The code I'm using is:
<img src="images/image<?php echo rand(1,9)); ?>.jpg" />
All my images follow the naming convention of image*n*.jpg where n is incremented through the file names. As far as I'm aware, I see no reason for this code not to generate a random image on the page. All I get is a broken link image.
EDIT: Missed the closing quotation mark for the src tag. The code does have this and it doesn't work with it.
Upvotes: 0
Views: 888
Reputation: 5389
You missed the closing quotation mark for src
and you have an extra closing parenthesis. Here is the corrected code:
<img src="images/image<?php echo rand(1,9); ?>.jpg" />
Upvotes: 0
Reputation: 46602
You also may want to use mt_rand() as it is more random then rand() and will give you more of a chance that the images wont be repeated.
<img src="./images/image<?=mt_rand(1,9);?>.jpg" />
If you have a broken image then view the page source and the correct path to the image.
Upvotes: 2
Reputation: 4078
try like this
$imagename = "image" . rand(1, 9) . ".jpg";
<img src="images/<?php echo $imagename; ?>" />
Upvotes: 0