Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

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?
Avatar of glcummins
glcummins
Flag of United States of America image

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;
}
 
?>

Open in new window

SOLUTION
Avatar of glcummins
glcummins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hankknight

ASKER

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);
?>

Open in new window

Yes, that will work, and will allow you to start with as large a data set as desired.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial