PHP > 1 to 6 rand() > Go!

Associate
Joined
8 Aug 2008
Posts
302
Hi guys

Bit of an afternoon head fuddle, basically I've got 6 items and 3 spaces, so I want to randomly generate 3 numbers from 1 to 6 with no repeats, bang them into an array then use those to pull out the items corresponding to the numbers.

Help! Thanks :D
 
Something like...

$numbers= array("1","2","3","4","5","6");

$number1 = $numbers[array_rand($numbers)];
$number2 = $numbers[array_rand($numbers)];

while($number2==$number1)
{ $number2 = $numbers[array_rand($numbers)]; }

$number3 = $numbers[array_rand($numbers)];
while($number3 == $number2 || $number3 == $number1)
{ $number3 = $numbers[array_rand($numbers)]; }

Then you have your three digits, that are all different and randomly generated...

You might want to change the numbers to 0-5 if you're pulling items from an array though (because an array starts at item 0).
 
PHP:
$numbers = range(1,6);
shuffle($numbers);
$your_array = array($numbers[0], $numbers[1], $numbers[2]);

edit: oh balls, too slow :p
 
For the sake of throwing in a one liner
PHP:
$numbers = array(rand(1,6), rand(1,6), rand(1,6));

This doesn't necessarily produce three distinct numbers, though. What the OP is asking for isn't really three random numbers, but a random ordering of three numbers.
 
This doesn't necessarily produce three distinct numbers, though. What the OP is asking for isn't really three random numbers, but a random ordering of three numbers.

As I see, helps to read the question more carefully ;)

PHP:
$numbers = array_rand(range(1,6), 3);
 
Back
Top Bottom