creating a group of random numbers that are unique

Asked

Viewed 795 times

1

There is uniqid to create a unique group of characters, but this function uses letters and numbers. And I’ve already researched, only I haven’t found anything for just numbers. Does anyone know any way to accomplish this?

  • 1

    You want this? rand() or mt_rand()

  • I’ve tried to use this mt_rand so all the time of error

  • Rand already helps. But you can prevent the generated number from repeating?

  • 1

    Specify your attempts on the question, including the error you faced with the mt_rand(). [Edit] question.

3 answers

4


It all depends on what you mean by "unique" and what you will do with these numbers. In principle, uniqid() returns hexa values that you can convert to decimals:

$uid = hexdec(uniqid());

Another solution would be this:

$digitos = '0123456789';
$tamanho = 16; // por exemplo...
$uid = '';
for ($i = 0; $i < $tamanho; $i++) {
    $uid .= $digitos[rand(0, strlen($digitos) - 1)];
}

(Solution based in this code)

The result would be a 16-digit random numeric string, for example.

1

You can use microtime

microtime - Returns a Unix timestamp with microseconds


Depending on the purpose it can be a simple and viable alternative and with low risk of collision.

echo microtime();
0.97959400 1407273578

You can remove the . and the space

1

just go including the numbers in an array, checking first if it no longer exists in it.

$sorteados = array();

for($i = 0; $i <= 1000; ++$i) {
    do {
       $nr = rand(1000,10000);
    } while (in_array($nr,$sorteados));
    $sorteados[] = $nr;
}

print_r($sorteados);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.