rand() function that changes for each use

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
Aki
Forum Newbie
Posts: 8
Joined: Fri Jan 09, 2009 5:38 pm

rand() function that changes for each use

Post by Aki »

I want to have the possibility to show a few randomely choosen pictures from a folder, and thought I'd use rand() to pick them out. However, I realised that if I wrote

Code: Select all

$pic = rand(0,15);
echo "<img src='{$pic}.png'>
<img src='{$pic}.png'>
<img src='{$pic}.png'>";
I'd have the same picture written three times, as $pic doesn't change between these, only once - when the script loads. Is there a function or another way to have three DIFFERENT, randomely choosen pictures?

Thanks on forehand.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: rand() function that changes for each use

Post by onion2k »

Just call rand() 3 times.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: rand() function that changes for each use

Post by requinix »

If they have to be different, you're dealing with such a small set of numbers that

Code: Select all

$numbers = range(0, 15); shuffle($numbers);
should be fine. $numbers[X] will be a random number between zero and fifteen; this means you can pick whatever X you want, it doesn't have to be random.

Code: Select all

echo $numbers[0]; // this will be a random number
Post Reply