Jump to content

[SOLVED] Random numbers within a certain range that do not repeat.


purplenewt

Recommended Posts

Hi I am a bit new to php and have run into a problem, I need to generate a random number list on request from a user.

 

eg, user selects 20 so I would need to have 20 unique random numbers from a range of 1-500.

 

I tried to work things out and eventually after much trial and error, searching and deleting I found this here which is using random range and shuffle.

Unfortunately this gives me 500 unique random numbers instead of 20 as I had hoped.

 

<?php
function rand_group() {
   $ary = range(1,500);
   shuffle($ary);
   return($ary);
}

echo implode(', ',rand_group(20));
?>

 

Any help would be great, this seems so close to what I need so I am thinking I am missing something really simple.

 

Purplenewt

Link to comment
Share on other sites

The problem with your implementation is that it uses a lot of memory. That said, you were close...

 

function rand_group($num) {
   $ary = range(1,500);
   shuffle($ary);
   return array_slice($ary, 0, $num);
}

echo implode(', ',rand_group(20));

 

 

EDIT:

If you're going to be using large numbers (near 500) your implementation may be best, but if you're going to stick with small numbers (near 20) it would be more memory efficient (though slower) to do..

 

function rand_group($num) {
$array = array();
while(count($array) < $num) {
	$randNum = rand(1,500);
	$array[$randNum] = $randNum;
}
return $array;
}

echo implode(', ', rand_group(20));

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.

Guest
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.