# 8 Unique Numbers

Hello,

I need to randomly generate 8 UNIQUE random numbers.

No number may be used more than once.

So this number is good:
53962471

This number is NOT because some numbers are duplicated:
11223344

What is the shortest/simplest way to do this?
LVL 16
###### Who is Participating?

Author Commented:
Or even better:
``````<?php
echo substr(str_shuffle('0123456789'),-8);
?>
``````
0

Commented:
Not sure that this method is the simplest, but it will definitely work and is extensible in case your requirements change:

``````<?php

\$uniqueNumbers = 8;
\$highestValue = 9;
\$lowestValue = 1;

\$arrGeneratedNumbers = array();

for (\$i = 0; \$i<\$uniqueNumbers; \$i++)
{
\$foundUnique = false;

while (!\$foundUnique)
{
\$newNumber = rand(\$lowestValue, \$highestValue);
if (!in_array(\$newNumber, \$arrGeneratedNumbers))
{
\$arrGeneratedNumbers[] = \$newNumber;
\$foundUnique = true;
}
}
}

foreach (\$arrGeneratedNumbers as \$number)
{
echo \$number;
}

?>
``````
0

Commented:
Here is a simpler method, but it limits you to the eight numbers that you enter into the array:
``````<?php

\$arrNumbers = array(1,2,3,4,5,6,7,8);

shuffle(\$arrNumbers);

foreach (\$arrNumbers as \$number)
{
echo \$number;
}

?>
``````
0

Commented:
Try this.
``````<?php

\$magicnumbers = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
\$randomnumber = '';

for(\$i = 0; \$i < 8; \$i++)
{
\$r = rand(0, 9 - \$i);
\$randomnumber .= \$magicnumbers[\$r];
unset(\$magicnumbers[\$r]);
\$magicnumbers = array_values(\$magicnumbers);
}

echo \$randomnumber;

?>
``````
0

Commented:
Is there a requirement for the length of the random numbers? Assuming NO
Are all digits 0-9 eligible? Assuming YES
Is zero acceptable? Assuming YES
``````<?php
\$uNums = array();
\$digits = array(1,2,3,4,5,6,7,8,9,0);
\$req = 8;
\$nCount = 0;
while (\$nCount < \$req) {
shuffle(\$digits); // randomly shuffle array of digits
\$nLen = rand(1,10);  // determine length of next random digit string
\$num = ""; // initialize digit string
for (\$i = 0; \$i < \$nLen; \$i++) { // collect \$nLen unique digits
\$num = \$num.\$digits[\$i];
}
if (!in_array(\$num, \$uNums)) { // verify digit string/number is not in array
\$uNums[] = \$num; // add digit string/number to array
\$nCount++;
}
}
?>
``````
0

Author Commented:
I feel silly answering my own question but the ideas keep getting more complex.

One of your ideas triggered a lightening bolt in my head and I came up with this.

What do you think?
``````<?php
\$str = '0123456789';
\$shuffled = str_shuffle(\$str);
echo substr(\$shuffled,-8);
?>
``````
0

Commented:
Yes, that will work, and will allow you to start with as large a data set as desired.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.