Random Numbers

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
ChessclubFriend
Forum Newbie
Posts: 21
Joined: Sun Mar 25, 2007 9:13 pm

Random Numbers

Post by ChessclubFriend »

I'm trying to generate 5 random numbers from a set of numbers. Is there an easy way to do this? Thanks in advance!

EDIT:
For instance, if I had the numbers 1,3,5,7,9,11, .., I want to randomly pick from only those numbers, nothing in between :)
thinsoldier
Forum Contributor
Posts: 367
Joined: Fri Jul 20, 2007 11:29 am
Contact:

Re: Random Numbers

Post by thinsoldier »

http://php.net/array_rand

Code: Select all

 
$options = '1,3,5,7,9,11,13,15,17,19';
$options = explode(',' , $options);
 
$rand_keys = array_rand($options , 5);
echo $options [$rand_keys[0]] . "\n";
echo $options [$rand_keys[1]] . "\n";
echo $options [$rand_keys[2]] . "\n";
echo $options [$rand_keys[3]] . "\n";
echo $options [$rand_keys[4]] . "\n";
 
Warning: I have no idea what I'm talking about.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Random Numbers

Post by s.dot »

Just put it into an array and shuffle it.

Code: Select all

$chars = array(1, 3, 5, 11, 79);
shuffle($chars);
 
echo $chars[0];  //or $chars[1] or 2 or 3 or 4.. you get the idea ;p
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
thinsoldier
Forum Contributor
Posts: 367
Joined: Fri Jul 20, 2007 11:29 am
Contact:

Re: Random Numbers

Post by thinsoldier »

Touché
Warning: I have no idea what I'm talking about.
Post Reply