Page 1 of 1

PHP Random Image

Posted: Thu Aug 21, 2008 2:49 pm
by BillBillJr

Code: Select all

<?php
$array = array(1 => 'img1.png', 2 => 'img2.png', 3 => 'img3.png', 4 => 'img4.png', 5 => 'img5.png');
$rand = rand(1, 5);
echo "<img src=\"" . $array[$rand] . "\">";
?>
So what do you think?
I've tested it, and it works. :)

Re: PHP Random Image

Posted: Thu Aug 21, 2008 3:50 pm
by onion2k
Pretty awful if I'm honest. You'd have to maintain both the array AND the random number range, the variable names are meaningless, plus you don't need half the code in order to do a better job. Just create a normal array of image names and shuffle it. Eg

Code: Select all

$images = array("1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg");
shuffle($images);
echo $images[0];

Re: PHP Random Image

Posted: Thu Aug 21, 2008 4:21 pm
by BillBillJr
Oh, cool, I didn't know you could shuffle images like that. XD