Jump to content

2 Random Numbers that cannot be the same?


Recommended Posts

I am trying to generate two random numbers, but have a check to make sure the first number isn't the same as the second.


The numbers will range between 1 and 12.


I have tried multiple ways of doing this, but cannot figure out an easy solution.  Any ideas?

Link to comment
Share on other sites

  • 1 month later...

$nums = array();

$min = 1;
$max = 10;

$total = 4;

if ( ($max-$min) < $total )
die('Let\'s avoid infinite loops...');

while ( count($nums) < $total ) {

$num = mt_rand($min, $max);
while ( in_array($num, $nums) )
	$num = mt_rand($min, $max);
$nums[] = $num;


print_r( $nums );


Link to comment
Share on other sites

Here's my favorite way


$max = 12;
$set = range(1,$max);
for ($i = 0; $i < 4; $i++) {
  $choice = rand(0,$max-1);
  $rand_set[] = $set[$choice];
  $set[$choice] = $set[$max-1];
print "Selected: " . implode(', ', $rand_set) . "\n";


The idea is to remove a random element, move the last element into that empty spot, then reduce the array size by 1.  This method works well for lower level languages like C also.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.