• 0

[PHP] How to generate unique random number?


Question

Hi,

I wanted to generate at least one thousand of unique 16-digit number using Random Number Function.

Like

1010101010000001

1234501010009801

9087651340298745

4390192836456106

I don't want the negative number. And I want the number to be exact 16-digit, for example, it should be 000000000002323, not 2323

I have scripted the code

echo "<table width=\"100\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
for ($i=0;$i<1000;$i++)
	{
echo "<tr><td>";
echo rand(0000000000000000,9999999999999999);
echo "</td></tr>";
	}
echo "</table>";

But I am not too sure on how to generate one thousand unqiue of 16-digit number using PHP code. Anyone of you who can help with this?

Thanks alot. :D

Oops! I realised that I posted in wrong section. Can any moderator please help moving this to correct section?

Thanks :blush:

Edited by Novawin

9 answers to this question

Recommended Posts

  • 0

The only way you can guarantee that the numbers you're generating will be unique is to store all of them in to an array, and then compare the newly generated random number against that array. If the number exists already, ignore it and generate another one, if it doesn't, add it to the array and then start again.

  • 0
<?php
$max = 1000;
$digits = 16;

$numbers = array();
$power = pow(10, $digits);

for($i=0;$i<$max;$i++)
{

	$num = str_pad(mt_rand(0, $power), $digits, "0", STR_PAD_LEFT);
	if (!in_array($num, $numbers))
		$numbers[] = $num;
	else
		$i--;
}

print_r($numbers);
?>

  • 0

Thanks all for your reply.

By the way, I tried to use array() inside PHP code as shown below

<?php

function number($length)
{
   $array = array();
   for($i=0;$i<$length;$i++)
	 $key .= rand(0,9);

   return $key;
}

echo "<table width=\"100\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
for ($i=0;$i<1000;$i++)
  {
  echo "<tr><td>";
  echo number(16);
  echo "</td></tr>";
  }
echo "</table>";

?>

This has met my requirement but some number are repeated. I want every number to be unique and it can't be repeated. Can anyone of you please help checking my code and try to modify as possible to only display every unique number?

Thanks alot! :D

Edited by Novawin
  • 0

Never mind about this. I found out that after I uploaded the webpage to Linux Server, all 16-digit number are unique whereas this webpage being tested on localhost on my Windows laptop, some numbers are repeated. This is so weird... But it's okie anyway. Thanks all for your help. :cool:

  • 0

it repeates due to it taking some information from the system clock IIRC. dont quote me on that but i think it takes one number from the system, which is sometimes repeated.

i think its something like that, and no matter what you do unless like stated you create an array then there is no way 2 generate a unique number everytime

  • 0

I am new to programming. Please I need help. I want to use the above codes for my project but I only need 12 digits. When I change the digits =12, the code generated the following error ; Warning: mt_rand(): max(-727379968) is smaller than min(0) in C:\xampp\htdocs\ITB\RECOS\Theme\random.php on line 11

I do not have any idea of what that means.

Thanks in advance.

  • 0
  On 24/08/2015 at 12:21, Osy Odife said:

I am new to programming. Please I need help. I want to use the above codes for my project but I only need 12 digits. When I change the digits =12, the code generated the following error ; Warning: mt_rand(): max(-727379968) is smaller than min(0) in C:\xampp\htdocs\ITB\RECOS\Theme\random.php on line 11

I do not have any idea of what that means.

Thanks in advance.

<?php
$max = 10;

$digits = 12;


$numbers = array();

$power = pow(10, $digits);


for($i=0;$i<$max;$i++){
 $num = str_pad(rand(0, $power), $digits, "0", STR_PAD_LEFT);
 if(!in_array($num, $numbers)){
  $numbers[] = $num;
 }else{
  $i--;
 }
}


print_r($numbers);

?>

Here's the code corrected code for 12 digits, the problem was with the mt_rand function, it only works with 2, 4, 8, 16, 32, 64 etc digits.

Welcome to neowin :D

 

Edit: something doesn't seem to work correctly, rewriting the code.

Edited by Seahorsepip
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft has known to toggle settings in Windows Updates.
    • Another Linux utility is being rewritten in Rust by David Uzondu Greenboot, the health check tool originally written in bash, is getting a rewrite in Rust, courtesy of engineers at Red Hat. This useful tool started in mid‑2018 as a Google Summer of Code project for Fedora IoT, designed to keep atomically updated systems from self-destructing after a bad update. At its heart, Greenboot is a framework that hooks into systemd to run health checks every time a machine boots. It looks for scripts in specific directories; anything in /etc/greenboot/check/required.d/ absolutely must pass. If a required script fails, Greenboot triggers a reboot to retry. After a few failed attempts, it executes scripts in /etc/greenboot/red.d/ and initiates a system rollback to the last known-good deployment, preventing an update from bricking your system. When all required checks succeed, it runs scripts from /etc/greenboot/green.d/ and marks the boot as successful by setting a GRUB environment variable. This whole process is kicked off by the greenboot-healthcheck.service before systemd's normal boot-complete.target is reached. As for why Red Hat is choosing this rewrite, it comes down to creating a more robust and secure utility. This is definitely not the only *-rs tool rewrite we have seen lately; you have probably heard about sudo-rs, which is a project to build a memory-safe replacement for the classic sudo utility. Building these fundamental system components in a memory-safe language like Rust helps eliminate entire categories of security vulnerabilities. According to the official Fedora change proposal, the rewrite expands support for both bootc and rpm-ostree based systems, whereas the original Bash version was built only for rpm-ostree. Red Hat developers have submitted a proposal to ship this new Rust version in Fedora 43. According to Phoronix, while the plan still needs a final vote from the Fedora Engineering and Steering Committee, it looks very likely to be approved. For current Fedora IoT users, the change promises to be a simple, seamless upgrade.
    • Elden Ring Nightreign will finally gain ‘Duo Expeditions' next week by Pulasthi Ariyasinghe FromSoftware's latest project, Elden Ring Nightreign, delivered a multiplayer-focused experience for the first time. While the title offered solo runs as an alternative to its standard three-player Trio Expeditions, Duos were surprisingly missing at launch. A couple of months later, the developer is finally delivering this highly requested feature for the hit roguelike. On social media, the studio confirmed that Duo Expeditions will be hitting Elden Ring Nightreign with the next update, patch 1.02, for the game on July 30. Check out the newly released trailer showing off this mode below. As we mentioned in our review of Elden Ring Nightreign, everything from enemy health, boss aggression, player damage, and even XP gain changes depending on how many players are in the Expedition. A post-launch update even tweaked the difficulty to favor solos as well. Duos should have the same changes being applied, with the mode being easier than trios but harder than solos to complete. Making sure the difficulty is properly balanced has previously been given as the reason why the Duos mode has taken a while to come in. FromSoftware also confirmed that patch 1.02 will have a range of more quality-of-life improvements on the UI side. This will include more Relics filtering options, making custom builds easier to construct before going on new runs, as seen below. Publisher Bandai Namco also announced this week that the Elden Ring Shadow of the Erdtree expansion for the original open-world Soulslike recently passed 10 million players. Meanwhile, this Elden Ring Nightreign spin-off now has over 5 million players, making both massive successes for the publisher. While FromSoftware is now focusing on other projects, Bandai Namco isn't done with the Elden Ring universe just yet either, as a live-action movie has now been confirmed to be in development too.
    • Or you ignore the part where @Michael Scrip answered you directly.
    • The reasons for Microsoft being in near perpetual state of reorganization for two years is due to the 6 CapEx acquisitions between Jan 2022 and Jan 2023, Blizzard, Oribi, Minit, Miburo, Lumenisity and Fungible. There were 15 CapEx acquisitions in 2021 alone. Much like the Borg, Microsoft assimilates knowledge instead of expending resources on learning and development. 10 gaming companies, 3 AI and 1 data modeling companies since 2018. But then this is in the founding DNA of Microsoft, MS DOS wasn't made by MS, Windows was based on the Apple Mac and Xerox PARC Alto....and on and on. (To be fair Apple's Lisa and Mac were from the Alto also)
  • Recent Achievements

    • Very Popular
      d4l3d earned a badge
      Very Popular
    • Dedicated
      Stephen Leibowitz earned a badge
      Dedicated
    • Dedicated
      Snake Doc earned a badge
      Dedicated
    • One Month Later
      Philsl earned a badge
      One Month Later
    • One Month Later
      armandointerior640 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      624
    2. 2
      ATLien_0
      240
    3. 3
      Xenon
      163
    4. 4
      neufuse
      123
    5. 5
      +FloatingFatMan
      123
  • Tell a friend

    Love Neowin? Tell a friend!