# 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?

##### Share on other sites

If it is just 2 number, you can try this:

```<?php
\$a = \$b = rand(1,12);
while (\$b == \$a) \$b=rand(1,12);
?>```

##### Share on other sites

• 1 month later...

Alright, I have tried everything on this one.  Now I need 4 random numbers that can't be the same.  I just cannot seem to figure this out.

##### Share on other sites

```<?php

\$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 );

?>```

##### Share on other sites

```<?php
\$set = range(1,12);
shuffle(\$set);
\$rand_set = array_slice(\$set,0,4);```

##### 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];
\$max--;
}
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.

##### Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account. ×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.