generate 3 random (not same) numbers within 1 to 20

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
mit
Forum Commoner
Posts: 32
Joined: Mon Sep 15, 2008 6:37 am

generate 3 random (not same) numbers within 1 to 20

Post by mit »

i need to generate 3 number like 4,15,19 or 17,01,11 the numbers should not be same
can any one help me?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: generate 3 random (not same) numbers within 1 to 20

Post by requinix »

Use range to create an array of numbers one through twenty and array_rand to pick three random ones (they will be unique).
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: generate 3 random (not same) numbers within 1 to 20

Post by Apollo »

Code: Select all

function GetRandomNrs( $min=1, $max=20, $num=3 )
{
    if ($num > $max-$min+1) $num = $max-$min+1;
 
    $result = array();
    for ($i=0; $i<$num; $i++)
    {
        do
        {
            $x = mt_rand($min,$max);
        }
        while (in_array($x,$result));
        $result[] = $x;
    }
    return $result;
}
If you'd be picking random unique values from an array, the array_rand function is your friend.

For low numbers of possibilities (as in your case 1 to 20), the range function mentioned by tasairis is easier. If you want to pick 3 numbers between 1 and 100.000.000, the above function is faster.
mit
Forum Commoner
Posts: 32
Joined: Mon Sep 15, 2008 6:37 am

Re: generate 3 random (not same) numbers within 1 to 20

Post by mit »

thx a lot , it s working perfectly ... :drunk:
Post Reply