PHP Random Image

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
BillBillJr
Forum Newbie
Posts: 9
Joined: Tue Aug 19, 2008 7:43 pm
Location: U.S.A.

PHP Random Image

Post 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. :)
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: PHP Random Image

Post 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];
BillBillJr
Forum Newbie
Posts: 9
Joined: Tue Aug 19, 2008 7:43 pm
Location: U.S.A.

Re: PHP Random Image

Post by BillBillJr »

Oh, cool, I didn't know you could shuffle images like that. XD
Post Reply