Hey guys

I am getting a random number using built in function in a given range of number, like between 300 to 10000. but i want to make sure random number should not be repeated, e.g. if rand() function has output 305 once, it should not come again,

for this i am storing each random number in table and how should i send back the control of previous line to get another number if new random number is already in table?

i mean how to get a unique random number just once in a given range using php.

thanks.

$rands = range(300, 10000);
shuffle($rands);

$random1 = array_pop($rands);
$random2 = array_pop($rands);
$random3 = array_pop($rands);
...
commented: I like that :) +13

may be the solution in saving the generated random value in database then when generate any new value, if founded in database your code ignore it and run the random function again
you can use mt_rand() than rand() for better random values

your solution may be help full but is there a way to go back to previous line and then start executing the same line of code again if random value is present in the table
for example

1. random()
2 value checked in table and found and now control of the execution should start from the line one again.

how to send back the control to line 1 again?

Make sure you make column of your table PK or unique, so when u insert any duplicate number, query will fail.

do
{
   $no=rand(300,1000);
   $insert="insert into table(column)values ($no)";
   $query=mysql_query($insert);
   if($query)//
   {
     $found=true;
   }
   else 
   {
     $found=false;
   }
}while(!found);

Kindly check mysql syntax, My code may have syntax error;

commented: excellent +3

the syntax is correct but this code is not looking for another random number repeatedly if one is already found in the table.
It should search for another random number again till one rand number is not found which is not in the table.

Why not use my solution?
It guarantees no two equal randoms and doesn't require database queries.

Member Avatar for diafol

ditto Insensus

Can't see what on earth all that phaffing about is for. Not even an acknowledgement. His loss. I like to put people on my ignore list. It saves wasting time in the future.

:)

To send it back use if statement, so if the (random value) founded in database colum run this rand() again elseif not founded in database then insetr it's value in database and "echo" this value on screen or any other procedure you want

Why not use my solution?
It guarantees no two equal randoms and doesn't require database queries.

I think user want the solution across the sessions. without database and using only php code user may end up using duplicates values.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.